unit Unit_PluginBackUpForm;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, RzButton, ExtCtrls, RzPanel, DB, MemDS, DBAccess, MyAccess, cxLocalization,IniFiles, RzPrgres, DADump, MyDump, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxCustomData,
  cxStyles, cxTL, cxMaskEdit, cxTLdxBarBuiltInMenu, dxSkinsCore, dxSkinMoneyTwins, cxInplaceContainer, cxDBTL, cxTLData, RzRadGrp,
  StdCtrls, RzEdit;

type
  TBACKUPFORM = class(TForm)
    RzPanel1: TRzPanel;
    cxLocalizer1: TcxLocalizer;
    db: TMyConnection;
    DS_Scan: TDataSource;
    Q_SCAN: TMyQuery;
    OpenDialog1: TOpenDialog;
    PB1: TRzProgressBar;
    SaveDialog1: TSaveDialog;
    MyDump1: TMyDump;
    CGTables: TRzCheckGroup;
    MLog: TRzMemo;
    RzPanel3: TRzPanel;
    BtnStart: TRzButton;
    BtnCancel: TRzButton;
    procedure FormActivate(Sender: TObject);
    procedure FormKeyPress(Sender: TObject; var Key: Char);
    procedure FormCreate(Sender: TObject);
    procedure BtnStartClick(Sender: TObject);
    procedure MyDump1BackupProgress(Sender: TObject; ObjectName: string; ObjectNum, ObjectCount, Percent: Integer);
    procedure FormResize(Sender: TObject);
    procedure SetLang(lng:string);
  private
   procedure WMGetSysCommand(var message : TMessage); message WM_SYSCOMMAND;
   procedure CreateParams(var params: TCreateParams); override;

  public
   tmppath: string;
   CallForm: thandle;
   backup: boolean;

   pl_fl1_0000,pl_fl1_0001,pl_fl1_0002,pl_fl1_0003,pl_fl1_0004,
   pl_fl1_0005,pl_fl1_0006,pl_fl1_0007,pl_fl1_0008,pl_fl1_0009,
   pl_fl1_0010,pl_fl1_0011,pl_fl1_0012,pl_fl1_0013,pl_fl1_0014,
   pl_fl1_0015,pl_fl1_0016,pl_fl1_0017,pl_fl1_0018,pl_fl1_0019,
   pl_fl1_0020,pl_fl1_0021,pl_fl1_0022,pl_fl1_0023,pl_fl1_0024,
   pl_fl1_0025,pl_fl1_0026,pl_fl1_0027,pl_fl1_0028,pl_fl1_0029,
   pl_fl1_0030: string;

   procedure BackUpMainData(filename: string);
   procedure BackUpAddData(filename: string);
   function RestoreAll: boolean;
   function BackUpAll: boolean;
   procedure ImportGroup(groupname,groupid,groupidparrent: string);
   function SetBackUpTable: string;
   function istable(s: string):boolean;
//   procedure PrepareSQL(filenamein,filenameout:string);
   function IfTableExist(tablename: string): boolean;
   procedure AddLog(s: WideString;outtime: boolean=true);
  end;

var
  BACKUPFORM: TBACKUPFORM;

implementation

{$R *.dfm}

uses plug_misc;


procedure TBACKUPFORM.AddLog(s: WideString;outtime: boolean=true);
begin
  if outtime
   then MLOG.Lines.Add(timetostr(now) + ': ' + s)
   else MLOG.Lines.Add(s);
end;

procedure TBACKUPFORM.WMGetSysCommand(var message : TMessage) ;
begin
 if (message.wParam = SC_MINIMIZE)
  then SendMessage(callform, wm_User, 0, 0)
  else inherited;
end;

procedure TBACKUPFORM.Createparams(var params: TCreateParams);
var
 aHWnd: HWND;
begin
 inherited;
 {как-нибудь получаем существующий дескриптор}
 ahWnd := GetForegroundWindow;
 {а теперь:}
 params.WndParent := ahWnd;
end;

function TBACKUPFORM.istable(s: string):boolean;
var
 i: integer;
begin
 result:=false;
 for i:=0 to 6 do
  if ((s='mlrating') and CGTables.Checks[0].Checked) or
     ((s='mluserkeyword') and CGTables.Checks[1].Checked) or
     ((s='mluserprim') and CGTables.Checks[2].Checked) or
     ((s='mldownloaddata') and CGTables.Checks[3].Checked) or
     ((s='mlnews') and CGTables.Checks[4].Checked) or
     ((s='mlnewsname') and CGTables.Checks[4].Checked)or
     ((s='mldownload') and CGTables.Checks[5].Checked) or
     ((s='mlgroup') and CGTables.Checks[6].Checked) or
     ((s='mlgroupname') and CGTables.Checks[6].Checked)
   then result:=true;
end;

(*
procedure TBACKUPFORM.PrepareSQL(filenamein,filenameout:string);
var
 l,l1: tstringlist;
 i: integer;
 s: string;
 f: textfile;
 b,u: boolean;
begin
// Memo1.Clear;
 l:=TStringList.Create;
 l.LoadFromFile(filenamein);
 assignfile(f,filenameout);
 rewrite(f);
 u:=true;
 for i:=0 to l.Count-1 do
  begin
   s:=l[i];
   if (pos('/*!',s)>0)
    then writeln(f,s)
    else
     begin
      writeln(f,'');
      break;
     end;
  end;
 b:=false;
 for i:=0 to l.Count-1 do
  begin
   s:=l[i];
   if pos('DROP TABLE IF EXISTS',s)>0
    then
     begin
      delete(s,1,20);
      s:=trim(s);
      delete(s,length(s),1);
      if istable(s)
       then
        begin
         if ((s='mlgroup')or(s='mlgroupname')or(s='mldownload'))and u
          then
           begin
            u:=false;
            writeln(f,'');
            writeln(f,'DROP DATABASE IF EXISTS importtmp;');
            writeln(f,'CREATE DATABASE IF NOT EXISTS importtmp;');
            writeln(f,'USE importtmp;');
            writeln(f,'');
           end;
         b:=true;
//         Memo1.Lines.Add(s);
        end;
     end;
   if pos('UNLOCK TABLES',s)>0
    then
     begin
      if b then
       begin
        writeln(f,l[i]);
        writeln(f,'');
        b:=false;
       end;
     end;
   if b then writeln(f,l[i]);
  end;
 writeln(f,'');
 l1:=TStringList.Create;
 for i:=l.Count-1 downto 0 do
  begin
   s:=l[i];
   if (pos('/*!',s)>0)
    then l1.Add(s)
    else break;
  end;
 for i:=l1.Count-1 downto 0 do writeln(f,l1[i]);
 l1.Free;
 closefile(f);
 l.Free;
end;
*)

function TBACKUPFORM.SetBackUpTable: string;
var
 s: string;
begin
 s:='';
 if CGTables.Checks[0].Checked then s:=s+',mlrating';
 if CGTables.Checks[1].Checked then s:=s+',mluserkeyword';
 if CGTables.Checks[2].Checked then s:=s+',mluserprim';
 if CGTables.Checks[3].Checked then s:=s+',mldownloaddata';
 if CGTables.Checks[4].Checked then s:=s+',mlnews,mlnewsname';
 if s<>'' then delete(s,1,1);
 result:=s;
end;

procedure TBACKUPFORM.BackUpMainData(filename: string);
var
 mydump:TMyDump;
 s: string;
 f: textfile;
begin
 s:=SetBackUpTable;
 if s<>''
  then
   begin
    mydump:=TMyDump.Create(self);
    try
     mydump.Connection:=db;
     mydump.OnBackupProgress:=MyDump1BackupProgress;
     mydump.Objects:=[doTables,doData];
     mydump.Options.AddDrop:=true;
     mydump.Options.AddLock:=true;
     mydump.Options.CompleteInsert:=true;
     mydump.Options.DisableKeys:=true;
     mydump.Options.GenerateHeader:=false;
     mydump.Options.InsertType:=itInsertIgnore;
     mydump.Options.UseExtSyntax:=true;
     mydump.TableNames:=s;
     try
      mydump.Backup;
     except
      on E : Exception do
      AddLog(pl_fl1_0013+' '+E.Message);
     end;
     AssignFile(f,filename);
     Append(f);
     write(f,MyDump.SQL.Text);
     closefile(f);
    except
    end;
    mydump.Free;
   end;
end;

procedure TBACKUPFORM.BackUpAddData(filename: string);
var
 f: textfile;
 mydump:TMyDump;
begin
 if not (CGTables.Checks[5].Checked or CGTables.Checks[6].Checked) then exit;
 AssignFile(f,filename);
 Append(f);
 db.Database:='mllbr_main';
 // mldownload
 if CGTables.Checks[5].Checked
  then
   begin
    try
     mydump:=TMyDump.Create(self);
     try
      mydump.Connection:=db;
      mydump.OnBackupProgress:=MyDump1BackupProgress;
      mydump.Objects:=[doTables,doData];
      mydump.Options.AddDrop:=true;
      mydump.Options.AddLock:=true;
      mydump.Options.CompleteInsert:=true;
      mydump.Options.DisableKeys:=true;
      mydump.Options.GenerateHeader:=false;
      mydump.Options.InsertType:=itInsertIgnore;
      mydump.Options.UseExtSyntax:=true;
      mydump.TableNames:='mllbr_main.mldownload';
      try
       mydump.BackupQuery('select bookid,library,title,FullName,seqname,genrenamerus,filesize,lang,ext,dl_position,dl_done,dl_date,dl_msg from `mllbr_main`.`mldownload` where library="'+plug_misc.BaseName+'"');
      except
       on E : Exception do
       AddLog(pl_fl1_0013+' '+E.Message);
      end;
      write(f,MyDump.SQL.Text);
     except
     end;
     mydump.Free;
    except
    end;
   end;
 // mlgroupname, mlgroup
 if CGTables.Checks[6].Checked
  then
   begin
    try
     mydump:=TMyDump.Create(self);
     try
      mydump.Connection:=db;
      mydump.OnBackupProgress:=MyDump1BackupProgress;
      mydump.Objects:=[doTables,doData];
      mydump.Options.AddDrop:=true;
      mydump.Options.AddLock:=true;
      mydump.Options.CompleteInsert:=true;
      mydump.Options.DisableKeys:=true;
      mydump.Options.GenerateHeader:=false;
      mydump.Options.InsertType:=itInsertIgnore;
      mydump.Options.UseExtSyntax:=true;
      mydump.TableNames:='mllbr_main.mlgroupname';
      try
       mydump.BackupQuery('select * from mllbr_main.mlgroupname');
      except
        on E : Exception do
        AddLog(pl_fl1_0013+' '+E.Message);
      end;
      write(f,MyDump.SQL.Text);
     except
     end;
     mydump.Free;
    except
    end;
    try
     mydump:=TMyDump.Create(self);
     try
      mydump.Connection:=db;
      mydump.OnBackupProgress:=MyDump1BackupProgress;
      mydump.Objects:=[doTables,doData];
      mydump.Options.AddDrop:=true;
      mydump.Options.AddLock:=true;
      mydump.Options.CompleteInsert:=true;
      mydump.Options.DisableKeys:=true;
      mydump.Options.GenerateHeader:=false;
      mydump.Options.InsertType:=itInsertIgnore;
      mydump.Options.UseExtSyntax:=true;
      mydump.TableNames:='mllbr_main.mlgroup';
      try
       mydump.BackupQuery('select bookid,groupid,library,date_gr from `mllbr_main`.`mlgroup` where library="'+plug_misc.BaseName+'"');
      except
       on E : Exception do
       AddLog(pl_fl1_0013+' '+E.Message);
      end;
      write(f,MyDump.SQL.Text);
     except
     end;
     mydump.Free;
    except
    end;
   end;
 CloseFile(f);
end;

function TBACKUPFORM.BackUpAll: boolean;
var
 f: textfile;
begin
 DB.Close;
 DB.Options.UseUnicode:=false;
 DB.Open;
 SaveDialog1.FileName:=plug_misc.BaseName+'_'+FormatDateTime('yymmddhhmmss',now);
 if SaveDialog1.Execute
  then
   begin
    result:=true;
    BtnCancel.ModalResult:=mrOk;
    AssignFile(f,SaveDialog1.FileName);
    Rewrite(f);
    writeln(f,'');
    writeln(f,'DROP DATABASE IF EXISTS importtmp;');
    writeln(f,'CREATE DATABASE IF NOT EXISTS importtmp;');
    writeln(f,'USE importtmp;');
    writeln(f,'');
    closefile(f);
    AddLog(pl_fl1_0014);
    BackUpMainData(SaveDialog1.FileName);
    AddLog(pl_fl1_0015);
    BackUpAddData(SaveDialog1.FileName);
    PB1.Percent:=100;
    AddLog(pl_fl1_0016);
    AddLog(pl_fl1_0017+' "'+SaveDialog1.FileName+'".');
   end
  else result:=false;
end;

procedure TBACKUPFORM.ImportGroup(groupname,groupid,groupidparrent: string);
var
 q: TMyQuery;
 gr: string;
begin
 q:=TMyQuery.Create(nil);
 q.Connection:=db;
 q.SQL.Text:='select * from `mllbr_main`.`mlgroupname` where groupid='+groupid;
 try
  q.open;
 except
  on E : Exception do
  AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
 end;
 if q.RecordCount>0
  // если такой ID группы существует
  then
   begin
    if q.FieldByName('groupname').AsString=groupname
     // если имя группы соответствует ID
     then
      begin
       // присваиваем полям groupidnew и groupidparrentnew те же значения
       q.SQL.Text:='update ignore `importtmp`.`mlgroupname` set groupidnew=groupid, groupidparrentnew=groupidparrent where groupid='+groupid+';';
       try
        q.execute;
       except
         on E : Exception do
         AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
       end;
       gr:=groupid;
      end
     // если имя группы не соответствует ID
     else
      begin
       // Проверяем наличие группы с таким именем и указанным groupidparrent
       q.SQL.Text:='select * from `mllbr_main`.`mlgroupname` where groupidparrent='+groupidparrent+' and groupname="'+groupname+'";';
       try
        q.open;
       except
         on E : Exception do
         AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
       end;
       if q.RecordCount>0
        // если группа с таким именем существует
        then
         begin
          // присваиваем полям groupidnew новое значении и groupidparrentnew - то же, что и было
          gr:=q.FieldByName('groupid').AsString;
          q.SQL.Text:='update ignore `importtmp`.`mlgroupname` set groupidnew='+gr+', groupidparrentnew=groupidparrent where groupid='+groupid+';';
          try
           q.execute;
          except
           on E : Exception do
           AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
          end;
         end
        // если группа с таким именем не существует
        else
         begin
          // создаем группу в основной таблице, присваиваем полям groupidnew новое значении и groupidparrentnew - то же, что и было
          q.SQL.Text:='insert ignore into `mllbr_main`.`mlgroupname` values (null,'+groupidparrent+',"'+groupname+'")';
          try
           q.execute;
          except
           on E : Exception do
           AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
          end;
          q.SQL.Text:='select * from `mllbr_main`.`mlgroupname` where groupidparrent='+groupidparrent+' and groupname="'+groupname+'";';
          try
           q.open;
          except
           on E : Exception do
           AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
          end;
          gr:=q.FieldByName('groupid').AsString;
          q.SQL.Text:='update ignore `importtmp`.`mlgroupname` set groupidnew='+gr+' where groupid='+gr+';';
          try
           q.execute;
          except
           on E : Exception do
           AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
          end;
         end;
      end;
   end
  // если такой ID группы не существует
  else
   begin
    // Проверяем наличие группы с таким именем и указанным groupidparrent
    q.SQL.Text:='select * from `mllbr_main`.`mlgroupname` where groupidparrent='+groupidparrent+' and groupname="'+groupname+'";';
    try
     q.open;
    except
     on E : Exception do
     AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
    end;
    if q.RecordCount>0
     // если группа с таким именем существует
     then
      begin
       // присваиваем полям groupidnew новое значении и groupidparrentnew - то же, что и было
       gr:=q.FieldByName('groupid').AsString;
       q.SQL.Text:='update ignore `importtmp`.`mlgroupname` set groupidnew='+gr+', groupidparrentnew=groupidparrent where groupid='+groupid+';';
       try
        q.execute;
       except
         on E : Exception do
         AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
       end;
      end
     // если группа с таким именем не существует
     else
      begin
       // создаем группу, присваиваем полям groupidnew новое значении и groupidparrentnew - то же, что и было
       q.SQL.Text:='insert ignore into `mllbr_main`.`mlgroupname` values (null,'+groupidparrent+',"'+groupname+'")';
       try
        q.execute;
       except
         on E : Exception do
         AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
       end;
       q.SQL.Text:='select * from `mllbr_main`.`mlgroupname` where groupidparrent='+groupidparrent+' and groupname="'+groupname+'";';
       try
        q.open;
       except
         on E : Exception do
         AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
       end;
       gr:=q.FieldByName('groupid').AsString;
       q.SQL.Text:='update ignore `importtmp`.`mlgroupname` set groupidnew='+gr+' where groupid='+groupid+';';
       try
        q.execute;
       except
         on E : Exception do
         AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
       end;
      end;
   end;
 // Изменяем groupidparrentnew у групп с groupidparrent=groupid
 q.SQL.Text:='update ignore `importtmp`.`mlgroupname` set groupidparrentnew='+gr+' where groupidparrent='+groupid+';';
 try
  q.execute;
 except
  on E : Exception do
  AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
 end;
 q.SQL.Text:='update ignore `importtmp`.`mlgroup` set groupidnew='+gr+' where groupid='+groupid;
 try
  q.execute;
 except
  on E : Exception do
  AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
 end;
 q.Free;
end;

procedure ShowChilds(Node: TcxTreeListNode);
var
 Child: TcxTreeListNode;
begin
 Child := Node.GetFirstChild;
 while Assigned(Child) do
  begin
   BACKUPFORM.ImportGroup(VarToStr(Child.Texts[0]),VarToStr(Child.Texts[1]),VarToStr(Child.Texts[2]));
   ShowChilds(Child);
   Child := Node.GetNextChild(Child)
  end;
end;

function TBACKUPFORM.IfTableExist(tablename: string): boolean;
var
 i: integer;
 q: TMyQuery;
begin
 Result := false;
 q:=TMyQuery.Create(nil);
 try
  q.Connection:=db;
  q.SQL.Text := 'use `importtmp`;';
  q.SQL.Add('show tables;');
  try
   q.Open;
  except
   on E : Exception do
   AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
  end;
  q.First;
  for i := 0 to q.RecordCount - 1 do
   begin
    if AnsiLowerCase(q.Fields[0].AsString) = AnsiLowerCase(tablename)
     then
      begin
       Result := True;
       exit;
      end;
     q.next;
    end;
 except
 end;
 q.Free;
end;

function TBACKUPFORM.RestoreAll: boolean;
var
 i: integer;
 tl: tcxDBTreeList;
 cl: TcxDBTreeListColumn;
 q: TMyQuery;
 s: string;
 b: boolean;
begin
 MLog.Clear;
 db.Database:=plug_misc.BaseName;
 db.Close;
 db.Options.UseUnicode:=false;
 db.Open;
 if opendialog1.Execute
  then
   begin
    AddLog(pl_fl1_0018+' "'+opendialog1.FileName+'".');
    result:=true;
    BtnCancel.ModalResult:=mrOk;
    MyDump1.TableNames:='';
    AddLog(pl_fl1_0019);
    MyDump1.RestoreFromFile(OpenDialog1.FileName);
    pb1.Percent:=100;
    db.Close;
    db.Options.UseUnicode:=true;
    db.Open;
    AddLog(pl_fl1_0020);
    for i:=0 to CGTables.Items.Count-1 do
     if CGTables.Checks[i].Checked then
       begin
        b:=true;
        case i of
         0: begin s:=pl_fl1_0002; b:=IfTableExist('mlrating');end;
         1: begin s:=pl_fl1_0003; b:=IfTableExist('mluserkeyword');end;
         2: begin s:=pl_fl1_0004; b:=IfTableExist('mluserprim');end;
         3: begin s:=pl_fl1_0021; b:=IfTableExist('mldownloaddata');end;
         4: begin s:=pl_fl1_0006; b:=IfTableExist('mlnews') and IfTableExist('mlnewsname');end;
         5: begin s:=pl_fl1_0007; b:=IfTableExist('mldownload');end;
         6: begin s:=pl_fl1_0008; b:=IfTableExist('mlgroup') and IfTableExist('mlgroupname');end;
        end;
        if not b then AddLog(pl_fl1_0022+' "'+s+'" '+pl_fl1_0023)
       end;
    q:=TMyQuery.Create(nil);
    try
     q.Connection:=db;
     if CGTables.Checks[5].Checked and IfTableExist('mldownload')
      then
       begin
        AddLog(pl_fl1_0024);
        q.SQL.Text:='update ignore importtmp.mldownload set library="'+db.Database+'";';
        try
         q.Execute;
        except
         on E : Exception do
         AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
        end;
        q.SQL.Text:='ALTER TABLE importtmp.mldownload DROP dl_id;';
        try
         q.Execute;
        except
         on E : Exception do
         AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
        end;
        q.SQL.Text:='select max(dl_position)as maxpos from `mllbr_main`.`mldownload` where dl_done="1"';
        try
         q.Execute;
        except
         on E : Exception do
         AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
        end;
       if q.FieldByName('maxpos').Value <> null
        then s := q.FieldByName('maxpos').AsString
        else s := '0';
        q.SQL.text:='SET @a:='+s+';';
        q.SQL.Add('update `importtmp`.`mldownload` set dl_position=@a:=(@a+10) where dl_done="1" order by dl_position;');
        try
         q.Execute;
        except
         on E : Exception do
         AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
        end;
       end;
     if CGTables.Checks[6].Checked and IfTableExist('mlgroupname') and IfTableExist('mlgroup')
      then
       begin
        AddLog(pl_fl1_0025);
        q.SQL.Text:='ALTER TABLE `importtmp`.`mlgroupname` ADD `groupidnew` INT UNSIGNED NOT NULL, ADD INDEX (groupidnew);';
        try
         q.Execute;
        except
         on E : Exception do
         AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
        end;
        q.SQL.Text:='ALTER TABLE `importtmp`.`mlgroupname` ADD `groupidparrentnew` INT UNSIGNED NOT NULL, ADD INDEX (groupidparrentnew);';
        try
         q.Execute;
        except
         on E : Exception do
         AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
        end;
        q.SQL.Text:='ALTER TABLE importtmp.mlgroup DROP uc_id;';
        try
         q.Execute;
        except
         on E : Exception do
         AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
        end;
        q.SQL.Text:='ALTER TABLE `importtmp`.`mlgroup` ADD `groupidnew` INT UNSIGNED NOT NULL, ADD INDEX (groupidnew);';
        try
         q.Execute;
        except
         on E : Exception do
         AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
        end;
        db.Database:=plug_misc.BaseName;
        Q_SCAN.SQL.Text:='select * from `importtmp`.`mlgroupname`';
        Q_SCAN.Open;
        try
         tl:=tcxDBTreeList.Create(self);
         tl.DataController.DataSource:=DS_Scan;
         tl.DataController.KeyField:='groupid';
         tl.DataController.ParentField:='groupidparrent';
         cl:=(tl.CreateColumn(nil) as TcxDBTreeListColumn);
         cl.DataBinding.FieldName:='groupname';
         cl:=(tl.CreateColumn(nil) as TcxDBTreeListColumn);
         cl.DataBinding.FieldName:='groupid';
         cl:=(tl.CreateColumn(nil) as TcxDBTreeListColumn);
         cl.DataBinding.FieldName:='groupidparrent';
         cl:=(tl.CreateColumn(nil) as TcxDBTreeListColumn);
         cl.DataBinding.FieldName:='groupidparrent';
         for I:=0 to tl.Count-1 do
          begin
           ImportGroup(VarToStr(tl.Items[i].Values[0]),VarToStr(tl.Items[i].Values[1]),VarToStr(tl.Items[i].Values[2]));
           if tl.Items[i].HasChildren
            then ShowChilds(tl.Items[i]);
          end;
         tl.DeleteAllColumns;
         tl.Free;
        except
         on E : Exception do
         AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
        end;
        q.SQL.Text:='update ignore `importtmp`.`mlgroup` set groupid=groupidnew, library="'+plug_misc.BaseName+'"';
        try
         q.execute;
        except
         on E : Exception do
         AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
        end;
        q.SQL.Text:='ALTER TABLE importtmp.mlgroup DROP groupidnew;';
        try
         q.Execute;
        except
         on E : Exception do
         AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
        end;
        q.SQL.Text:='update ignore `importtmp`.`mlgroupname` set groupid=groupidnew, groupidparrent=groupidparrentnew';
        try
         q.execute;
        except
         on E : Exception do
         AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
        end;
        q.SQL.Text:='ALTER TABLE importtmp.mlgroupname DROP groupidnew;';
        try
         q.Execute;
        except
         on E : Exception do
         AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
        end;
        q.SQL.Text:='ALTER TABLE importtmp.mlgroupname DROP groupidparrentnew;';
        try
         q.Execute;
        except
         on E : Exception do
         AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
        end;
        // -------------------------------------------------------------------------------
       end;
    except
    end;
    // Перенос данных в основные таблицы .....
    AddLog(pl_fl1_0026);
    if CGTables.Checks[0].Checked and IfTableExist('mlrating')
     then
      begin
       AddLog('   '+pl_fl1_0002,false);
       q.SQL.Text:='DROP TABLE IF EXISTS`'+plug_misc.BaseName+'`.`mlrating`';
       try
        q.Execute;
       except
         on E : Exception do
         AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
       end;
       q.SQL.Text:='RENAME TABLE `importtmp`.`mlrating` TO `'+plug_misc.BaseName+'`.`mlrating`';
       try
        q.Execute;
       except
         on E : Exception do
         AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
       end;
      end;
    if CGTables.Checks[1].Checked and IfTableExist('mluserkeyword')
     then
      begin
       AddLog('   '+pl_fl1_0003,false);
       q.SQL.Text:='DROP TABLE IF EXISTS`'+plug_misc.BaseName+'`.`mluserkeyword`';
       try
        q.Execute;
       except
         on E : Exception do
         AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
       end;
       q.SQL.Text:='RENAME TABLE `importtmp`.`mluserkeyword` TO `'+plug_misc.BaseName+'`.`mluserkeyword`';
       try
        q.Execute;
       except
         on E : Exception do
         AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
       end;
      end;
    if CGTables.Checks[2].Checked and IfTableExist('mluserprim')
     then
      begin
       AddLog('   '+pl_fl1_0004,false);
       q.SQL.Text:='DROP TABLE IF EXISTS`'+plug_misc.BaseName+'`.`mluserprim`';
       try
        q.Execute;
       except
         on E : Exception do
         AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
       end;
       q.SQL.Text:='RENAME TABLE `importtmp`.`mluserprim` TO `'+plug_misc.BaseName+'`.`mluserprim`';
       try
        q.Execute;
       except
         on E : Exception do
         AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
       end;
      end;
    if CGTables.Checks[3].Checked and IfTableExist('mldownloaddata')
     then
      begin
       AddLog('   '+pl_fl1_0021,false);
       q.SQL.Text:='DROP TABLE IF EXISTS`'+plug_misc.BaseName+'`.`mldownloaddata`';
       try
        q.Execute;
       except
         on E : Exception do
         AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
       end;
       q.SQL.Text:='RENAME TABLE `importtmp`.`mldownloaddata` TO `'+plug_misc.BaseName+'`.`mldownloaddata`';
       try
        q.Execute;
       except
         on E : Exception do
         AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
       end;
      end;
    if CGTables.Checks[4].Checked and IfTableExist('mlnews')and IfTableExist('mlnewsname')
     then
      begin
       AddLog('   '+pl_fl1_0006,false);
       q.SQL.Text:='DROP TABLE IF EXISTS`'+plug_misc.BaseName+'`.`mlnews`';
       try
        q.Execute;
       except
         on E : Exception do
         AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
       end;
       q.SQL.Text:='RENAME TABLE `importtmp`.`mlnews` TO `'+plug_misc.BaseName+'`.`mlnews`';
       try
        q.Execute;
       except
         on E : Exception do
         AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
       end;
       q.SQL.Text:='DROP TABLE IF EXISTS`'+plug_misc.BaseName+'`.`mlnewsname`';
       try
        q.Execute;
       except
         on E : Exception do
         AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
       end;
       q.SQL.Text:='RENAME TABLE `importtmp`.`mlnewsname` TO `'+plug_misc.BaseName+'`.`mlnewsname`';
       try
        q.Execute;
       except
         on E : Exception do
         AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
       end;
      end;
    if CGTables.Checks[5].Checked and IfTableExist('mldownload')
     then
      begin
       AddLog('   '+pl_fl1_0007,false);
       q.SQL.Text:='DELETE ignore FROM `mllbr_main`.`mldownload` where library="'+plug_misc.BaseName+'"';
       try
        q.Execute;
       except
         on E : Exception do
         AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
       end;
       q.SQL.Text:='insert ignore into `mllbr_main`.`mldownload` select null,importtmp.mldownload.* from importtmp.mldownload';
       try
        q.Execute;
       except
         on E : Exception do
         AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
       end;
      end;
    if CGTables.Checks[6].Checked and IfTableExist('mlgroup')and IfTableExist('mlgroupname')
     then
      begin
       AddLog('   '+pl_fl1_0008,false);
       q.SQL.Text:='DELETE ignore FROM `mllbr_main`.`mlgroup` where library="'+plug_misc.BaseName+'"';
       try
        q.Execute;
       except
         on E : Exception do
         AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
       end;
       q.SQL.Text:='insert ignore into `mllbr_main`.`mlgroup` select null,importtmp.mlgroup.* from importtmp.mlgroup';
       try
        q.Execute;
       except
         on E : Exception do
         AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
       end;
      end;
    // Удаляем временную базу
    AddLog(pl_fl1_0027);
    q.SQL.Text:='DROP DATABASE IF EXISTS importtmp;';
    try
     q.Execute;
    except
      on E : Exception do
      AddLog(pl_fl1_0013+' '+E.Message+#13+q.sql.Text);
    end;
    q.Free;
    AddLog(pl_fl1_0028);
   end
  else result:=false;
end;

procedure TBACKUPFORM.BtnStartClick(Sender: TObject);
begin
 if backup
  then
   begin
    BtnStart.Enabled:=false;
    BtnCancel.Enabled:=false;
    try
     BackUpAll;
    except
    end;
    BtnStart.Enabled:=true;
    BtnCancel.Enabled:=true;
   end
  else
   begin
    BtnStart.Enabled:=false;
    BtnCancel.Enabled:=false;
    try
     RestoreAll;
    except
    end;
    BtnStart.Enabled:=true;
    BtnCancel.Enabled:=true;
   end;
end;

procedure TBACKUPFORM.FormActivate(Sender: TObject);
begin
 if backup
  then BtnStart.Caption:=pl_fl1_0029
  else BtnStart.Caption:=pl_fl1_0030;
 if backup
  then Caption:=pl_fl1_0000+' '+plug_misc.BaseName
  else Caption:=pl_fl1_0001+' '+plug_misc.BaseName;
end;

procedure TBACKUPFORM.FormCreate(Sender: TObject);
var
 f: TIniFile;
 s,path,lng: string;
begin
 BtnCancel.ModalResult:=mrCancel;
 PB1.Percent:=0;
 s:=ChangeFileExt(Application.ExeName,'.ini');
 f:=TIniFile.Create(s);
 db.Port:=f.ReadInteger('MySQL','mysql_port', 3306);
 db.Username:=f.ReadString('MySQL','mysql_username','root');
 db.Password:=f.ReadString('MySQL','mysql_password','');
 db.Server:=f.ReadString('MySQL','mysql_server','localhost');
 path:=ExtractFilePath(Application.ExeName);
 lng:=f.ReadString('main','lang','Russian');
 if FileExists(path+lng+'.lng')
  then
   begin
    try
     cxLocalizer1.FileName:=path+lng+'.lng';
     cxLocalizer1.Active:=true;
     cxLocalizer1.LanguageIndex:=1;
    except
    end;
   end;
 f.Free;
 SetLang(path+lng+'.lng');
 f:=TIniFile.Create(INIFile);
 tmppath:=abs_path(IncludeTrailingBackslash(f.ReadString('main','tmppath','')));
 f.Free;
 BACKUPFORM:=self;
 Application.ProcessMessages;
 db.Database:=plug_misc.BaseName;
 db.Open;
 if  not db.Connected
  then
   begin
    BtnStart.Enabled:=false;
    //AddLog('Ошибка подключения к базе.');
    exit;
   end;
 BtnStart.Enabled:=true;
end;

procedure TBACKUPFORM.FormKeyPress(Sender: TObject; var Key: Char);
begin
 if Key=#27 then Close;
end;

procedure TBACKUPFORM.FormResize(Sender: TObject);
begin
 btnstart.Left:= rzpanel3.Width div 2 - btnstart.Width - 8;
 BtnCancel.Left:= rzpanel3.Width div 2 + 8;
end;

procedure TBACKUPFORM.MyDump1BackupProgress(Sender: TObject; ObjectName: string; ObjectNum, ObjectCount, Percent: Integer);
begin
 pb1.Percent:=Percent;
end;

procedure TBACKUPFORM.SetLang(lng:string);
var
 f: TMemIniFile;
 cp: word;
begin
 f:=TMemIniFile.Create(lng,TEncoding.GetEncoding(1251));
 cp:=f.ReadInteger('Custom Resource Strings','codepage',1251);
 f.free;
 f:=TMemIniFile.Create(lng,TEncoding.GetEncoding(cp));
 pl_fl1_0000:=f.ReadString('Custom Resource Strings','pl_fl1_0000','Экспорт личных данных');
 pl_fl1_0001:=f.ReadString('Custom Resource Strings','pl_fl1_0001','Импорт личных данных');
 pl_fl1_0002:=f.ReadString('Custom Resource Strings','pl_fl1_0002','Рейтинг');
 pl_fl1_0003:=f.ReadString('Custom Resource Strings','pl_fl1_0003','Ключевые слова');
 pl_fl1_0004:=f.ReadString('Custom Resource Strings','pl_fl1_0004','Примечания');
 pl_fl1_0005:=f.ReadString('Custom Resource Strings','pl_fl1_0005','Отметка "Скачано" в основных таблицах');
 pl_fl1_0006:=f.ReadString('Custom Resource Strings','pl_fl1_0006','Новинки');
 pl_fl1_0007:=f.ReadString('Custom Resource Strings','pl_fl1_0007','Менеджер закачек');
 pl_fl1_0008:=f.ReadString('Custom Resource Strings','pl_fl1_0008','Группы');
 pl_fl1_0009:=f.ReadString('Custom Resource Strings','pl_fl1_0009','Начать');
 pl_fl1_0010:=f.ReadString('Custom Resource Strings','pl_fl1_0010','Выход');
 pl_fl1_0011:=f.ReadString('Custom Resource Strings','pl_fl1_0011','Файлы резервного копирования');
 pl_fl1_0012:=f.ReadString('Custom Resource Strings','pl_fl1_0012','Все файлы');
 pl_fl1_0013:=f.ReadString('Custom Resource Strings','pl_fl1_0013','Ошибка.');
 pl_fl1_0014:=f.ReadString('Custom Resource Strings','pl_fl1_0014','Экспортируются данные основных таблиц.');
 pl_fl1_0015:=f.ReadString('Custom Resource Strings','pl_fl1_0015','Экспортируются данные общих таблиц.');
 pl_fl1_0016:=f.ReadString('Custom Resource Strings','pl_fl1_0016','Экспорт личных данных завершен.');
 pl_fl1_0017:=f.ReadString('Custom Resource Strings','pl_fl1_0017','Данные сохранены в файл');
 pl_fl1_0018:=f.ReadString('Custom Resource Strings','pl_fl1_0018','Импорт данных из');
 pl_fl1_0019:=f.ReadString('Custom Resource Strings','pl_fl1_0019','Загрузка данных во временную базу.');
 pl_fl1_0020:=f.ReadString('Custom Resource Strings','pl_fl1_0020','Обработка...');
 pl_fl1_0021:=f.ReadString('Custom Resource Strings','pl_fl1_0021','Скачано');
 pl_fl1_0022:=f.ReadString('Custom Resource Strings','pl_fl1_0022','Таблица');
 pl_fl1_0023:=f.ReadString('Custom Resource Strings','pl_fl1_0023','отсутствует в файле резервного копирования.');
 pl_fl1_0024:=f.ReadString('Custom Resource Strings','pl_fl1_0024','Обработка таблиц менеджера закачек');
 pl_fl1_0025:=f.ReadString('Custom Resource Strings','pl_fl1_0025','Обработка таблиц групп');
 pl_fl1_0026:=f.ReadString('Custom Resource Strings','pl_fl1_0026','Перенос данных в основные таблицы...');
 pl_fl1_0027:=f.ReadString('Custom Resource Strings','pl_fl1_0027','Удаляем временную базу.');
 pl_fl1_0028:=f.ReadString('Custom Resource Strings','pl_fl1_0028','Импорт данных завершен.');
 pl_fl1_0029:=f.ReadString('Custom Resource Strings','pl_fl1_0029','Экспорт');
 pl_fl1_0030:=f.ReadString('Custom Resource Strings','pl_fl1_0030','Импорт');
 f.Free;
 OpenDialog1.Filter:=pl_fl1_0011+'(*.sql)|*.sql|'+pl_fl1_0012+'(*.*)|*.*';
 SaveDialog1.Filter:=pl_fl1_0011+'(*.sql)|*.sql|'+pl_fl1_0012+'(*.*)|*.*';
 CGTables.Items[0]:=pl_fl1_0002;
 CGTables.Items[1]:=pl_fl1_0003;
 CGTables.Items[2]:=pl_fl1_0004;
 CGTables.Items[3]:=pl_fl1_0005;
 CGTables.Items[4]:=pl_fl1_0006;
 CGTables.Items[5]:=pl_fl1_0007;
 CGTables.Items[6]:=pl_fl1_0008;
 BtnCancel.Caption:=pl_fl1_0010;
end;

end.


