osapiutils
/
OSAPIUtils.pas
1078 строк · 32.1 Кб
1unit OSAPIUtils;
2
3{ Author: Pichugin Maksim }
4
5{2024-09-22}
6{2024-06-04}
7{2024-02-04}
8{2024-01-03}
9{2023-11-22}
10{2023-10-28}
11{2023-10-23}
12{2023-10-05}
13{2023-05-11}
14{2023-04-29}
15{2023-03-19}
16{2023-03-14}
17{2023-01-21}
18
19{$mode objfpc}{$H+}
20
21interface
22
23uses
24{$IFDEF WINDOWS}
25Windows, StdCtrls, ExtCtrls, Graphics,
26{$ENDIF}
27{$IFDEF UNIX}
28unix,baseunix,users,
29{$ENDIF}
30WinSock, JWAWindows,
31Registry, Forms, Classes, SysUtils, Dialogs, Controls, Buttons, Menus,
32LazUTF8, FileUtil, LazFileUtils;
33
34type
35TEXEVersionData = record
36CompanyName,
37FileDescription,
38FileVersion,
39InternalName,
40LegalCopyright,
41LegalTrademarks,
42OriginalFileName,
43ProductName,
44ProductVersion,
45Comments,
46PrivateBuild,
47SpecialBuild: string;
48end;
49
50//Active Directory User Data
51TADUserData = record
52ADUser :Boolean;
53// Fully qualified distinguished name
54NameFullyQualifiedDN :ShortString;
55// Windows NT® 4.0 account name
56NameSamCompatible :ShortString;
57// A "friendly" display name
58NameDisplay :ShortString;
59// GUID string that the IIDFromString function returns
60NameUniqueId :ShortString;
61// Complete canonical name
62NameCanonical :ShortString;
63// User principal name
64NameUserPrincipal :ShortString;
65
66NameCanonicalEx :ShortString;
67// Generalized service principal name
68NameServicePrincipal :ShortString;
69// DNS domain name, plus the user name
70DNSDomainName :ShortString;
71// The DNS domain name followed by a backward-slash and the SAM user name.
72NameDnsDomain :ShortString;
73// The first name or given name of the user.
74NameGivenName :ShortString;
75// The last name or surname of the user.
76NameSurname :ShortString;
77end;
78
79{
80
81}
82
83{ TNMDialogFormActions }
84
85TNMDialogFormActions = class
86private
87{ Private declarations }
88public
89procedure ButtonClose(Sender: TObject);
90procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
91end;
92
93{$IFDEF MSWINDOWS}
94const
95{$EXTERNALSYM IDI_HAND}
96IDI_HAND = MakeIntResource(OIC_HAND);
97{$EXTERNALSYM IDI_QUESTION}
98IDI_QUESTION = MakeIntResource(OIC_QUES);
99{$EXTERNALSYM IDI_EXCLAMATION}
100IDI_EXCLAMATION = MakeIntResource(OIC_WARNING);
101{$EXTERNALSYM IDI_ASTERISK}
102IDI_ASTERISK = MakeIntResource(OIC_INFORMATION);
103{$EXTERNALSYM IDI_WINLOGO}
104IDI_WINLOGO = MakeIntResource(OIC_WINLOGO);
105{$EXTERNALSYM IDI_WARNING}
106IDI_WARNING = IDI_EXCLAMATION;
107{$EXTERNALSYM IDI_ERROR}
108IDI_ERROR = IDI_HAND;
109{$EXTERNALSYM IDI_INFORMATION}
110IDI_INFORMATION = IDI_ASTERISK;
111{$EXTERNALSYM IDI_SHIELD}
112IDI_SHIELD = MakeIntResource(OIC_SHIELD);
113
114{$ENDIF MSWINDOWS}
115
116var
117SYSTEM_PATHVARS_INITED :Boolean=False; //OSGlobalPathVarInited
118SYSTEM_PATHVARS :TStringList;
119NMDialogFormActions :TNMDialogFormActions;
120
121{
122===Windows vars===
123
124%SystemDrive%
125
126CURRENT_USER
127
128%APPDATA%
129%LOCALAPPDATA%
130%USERDOMAIN%
131%USERNAME%
132%USERPROFILE%
133%HOMEDRIVE%
134
135%TEMP%
136%TMP%
137
138%USERLOCALLOW%
139%USERDOWNLOADS%
140
141LOCAL_MACHINE
142
143%ProgramData%
144%ProfilesDirectory%
145%Default%
146%Public%
147
148===Extended vars====
149
150Firebird DB
151
152%FirebirdProgramDirectory%
153}
154
155{FILES}
156
157function GetAbsolutSystemPath(var APath:String):Boolean;
158//Установка текущей директорией место размещения программы
159function ChangeCurrentDirectory: boolean;
160
161function PathExists(APath:String; ACreate:Boolean):boolean;
162
163{NETWORK}
164
165function GetLocalIP: string;
166function GetLocalHostname: string;
167
168{OTHER}
169
170function GetGUID: String;
171function GetCurrentUserName : String;
172function GetCurrentComputerName : String;
173function GetADUserData(var AOutData:TADUserData):Boolean;
174
175{APP}
176
177function StartApp(AFileName, AParams:String): Integer;
178function GetEXEVersionData(const FileName: string; var OutData:TEXEVersionData): Boolean;
179
180{DIALOGS}
181
182function ShowTaskDialog(AOwner:TComponent; AMsg: String; AMsgBoxFlags: Longint=MB_ICONINFORMATION):integer; overload;
183function ShowTaskDialog(AOwner:TComponent; AMsg: String; AWarningHint:String=''; AMsgBoxFlags: Longint=MB_ICONINFORMATION):integer; overload;
184procedure ShowTaskDialogNM(AMsg: String; AMsgBoxFlags: Longint=MB_ICONINFORMATION); overload;
185procedure ShowTaskDialogNM(AMsg: String; AWarningHint:String=''; AMsgBoxFlags: Longint=MB_ICONINFORMATION); overload;
186
187implementation
188
189procedure ShowTaskDialogNM(AMsg: String; AMsgBoxFlags: Longint=MB_ICONINFORMATION);
190begin
191ShowTaskDialogNM(AMsg, '', AMsgBoxFlags);
192end;
193
194procedure ShowTaskDialogNM(AMsg: String; AWarningHint:String=''; AMsgBoxFlags: Longint=MB_ICONINFORMATION);
195var
196IconHandle :HICON;
197WarnIconHandle :HICON;
198DForm :TForm;
199DPanelBottom :TPanel;
200DPanelWarningBottom :TPanel;
201DPanelMain :TPanel;
202DPanelMLeft :TPanel;
203WarnIconImage,
204IconImage :TImage;
205Button :TButton;
206MessageWarningText :TLabel;
207MessageText :TLabel;
208begin
209{$IFDEF MSWINDOWS}
210if IDI_WARNING<>nil then
211WarnIconHandle := LoadIcon(0,IDI_WARNING)
212else
213WarnIconHandle := 0;
214{$ELSE}
215WarnIconHandle := 0;
216{$ENDIF}
217
218case AMsgBoxFlags of
219MB_ICONINFORMATION:
220begin
221{$IFDEF MSWINDOWS}
222if IDI_INFORMATION<>nil then
223IconHandle := LoadIcon(0,IDI_INFORMATION)
224else
225IconHandle := 0;
226{$ELSE}
227IconHandle := 0;
228{$ENDIF}
229end;
230MB_ICONEXCLAMATION:
231begin
232{$IFDEF MSWINDOWS}
233if IDI_EXCLAMATION<>nil then
234IconHandle := LoadIcon(0,IDI_EXCLAMATION)
235else
236IconHandle := 0;
237{$ELSE}
238IconHandle := 0;
239{$ENDIF}
240end;
241MB_ICONERROR:
242begin
243{$IFDEF MSWINDOWS}
244if IDI_ERROR<>nil then
245IconHandle := LoadIcon(0,IDI_ERROR)
246else
247IconHandle := 0;
248{$ELSE}
249IconHandle := 0;
250{$ENDIF}
251end;
252end;
253
254if (Length(AMsg)>0) then
255begin
256DForm:=TForm.Create(Application);
257DForm.Caption:=Application.Title;
258//DForm.ParentWindow:=GetDesktopwindow;
259DForm.Width:=400;
260DForm.Height:=150;
261DForm.BorderStyle:=bsDialog;
262DForm.Position:=poWorkAreaCenter;//
263DForm.OnClose:=Addr(NMDialogFormActions.FormClose);
264DForm.ShowInTaskBar:=stAlways;
265DForm.FormStyle:=fsStayOnTop;
266//Bottoom
267
268if Length(AWarningHint)>0 then
269begin
270DPanelWarningBottom:=TPanel.Create(DForm);
271DPanelWarningBottom.Parent:=DForm;
272DPanelWarningBottom.Align:=alBottom;
273DPanelWarningBottom.Height:=32;
274DPanelWarningBottom.BevelOuter:=bvNone;
275DPanelWarningBottom.Show;
276
277WarnIconImage:=TImage.Create(DPanelWarningBottom);
278WarnIconImage.Parent:=DPanelWarningBottom;
279WarnIconImage.Align:=alLeft;
280WarnIconImage.AutoSize:=True;
281WarnIconImage.Width:=48;
282WarnIconImage.Center:=True;
283WarnIconImage.Transparent:=True;
284WarnIconImage.Proportional:=True;
285WarnIconImage.Stretch:=True;
286WarnIconImage.BorderSpacing.Top:=5;
287WarnIconImage.BorderSpacing.Left:=5;
288WarnIconImage.BorderSpacing.Bottom:=5;
289WarnIconImage.BorderSpacing.Right:=5;
290WarnIconImage.Picture.Icon.Handle:=WarnIconHandle;
291
292MessageWarningText:=TLabel.Create(DPanelWarningBottom);
293MessageWarningText.Parent:=DPanelWarningBottom;
294MessageWarningText.Caption:=AWarningHint;
295MessageWarningText.Align:=alClient;
296MessageWarningText.Alignment:=taLeftJustify;
297MessageWarningText.Layout:=tlCenter;
298MessageWarningText.Transparent:=True;
299MessageWarningText.WordWrap:=True;
300MessageWarningText.BorderSpacing.Top:=5;
301MessageWarningText.BorderSpacing.Left:=5;
302MessageWarningText.BorderSpacing.Bottom:=5;
303MessageWarningText.BorderSpacing.Right:=5;
304MessageWarningText.Show;
305end;
306
307DPanelBottom:=TPanel.Create(DForm);
308DPanelBottom.Parent:=DForm;
309DPanelBottom.Align:=alBottom;
310DPanelBottom.Height:=46;
311DPanelBottom.BevelOuter:=bvNone;
312DPanelBottom.Show;
313
314//Center
315DPanelMain:=TPanel.Create(DForm);
316DPanelMain.Parent:=DForm;
317DPanelMain.Align:=alClient;
318DPanelMain.BevelOuter:=bvNone;
319DPanelMain.Color:=clWindow;
320DPanelMain.Show;
321
322DPanelMLeft:=TPanel.Create(DPanelMain);
323DPanelMLeft.Parent:=DPanelMain;
324DPanelMLeft.Align:=alLeft;
325DPanelMLeft.Width:=64;
326DPanelMLeft.BevelOuter:=bvNone;
327DPanelMLeft.Color:=clWindow;
328DPanelMLeft.Show;
329
330IconImage:=TImage.Create(DPanelMLeft);
331IconImage.Parent:=DPanelMLeft;
332IconImage.Align:=alTop;
333IconImage.AutoSize:=True;
334IconImage.Height:=64;
335IconImage.Center:=True;
336IconImage.Transparent:=True;
337IconImage.Proportional:=True;
338IconImage.BorderSpacing.Top:=5;
339IconImage.BorderSpacing.Left:=5;
340IconImage.BorderSpacing.Bottom:=5;
341IconImage.BorderSpacing.Right:=5;
342IconImage.Picture.Icon.Handle:=IconHandle;
343
344Button:=TButton.Create(DPanelBottom);
345Button.Parent:=DPanelBottom;
346Button.Caption:='OK';
347Button.Cancel:=True;
348Button.Height:=24;
349Button.Width:=100;
350Button.Align:=alRight;
351Button.BorderSpacing.Top:=10;
352Button.BorderSpacing.Left:=10;
353Button.BorderSpacing.Bottom:=10;
354Button.BorderSpacing.Right:=10;
355Button.ModalResult:=mrClose;
356Button.OnClick:=Addr(NMDialogFormActions.ButtonClose);
357Button.Show;
358
359MessageText:=TLabel.Create(DPanelMain);
360MessageText.Parent:=DPanelMain;
361MessageText.Caption:=AMsg;
362MessageText.Align:=alClient;
363MessageText.Transparent:=True;
364MessageText.WordWrap:=True;
365MessageText.BorderSpacing.Top:=10;
366MessageText.BorderSpacing.Left:=10;
367MessageText.BorderSpacing.Bottom:=10;
368MessageText.BorderSpacing.Right:=10;
369MessageText.Show;
370
371if Length(AWarningHint)>0 then
372begin
373DPanelWarningBottom.Top:=DForm.Height;
374end;
375
376DForm.Show;
377end;
378end;
379
380function ShowTaskDialog(AOwner:TComponent; AMsg: String; AMsgBoxFlags: Longint): integer;
381begin
382Result:=ShowTaskDialog(AOwner, AMsg, '', AMsgBoxFlags);
383end;
384
385function ShowTaskDialog(AOwner:TComponent; AMsg: String; AWarningHint:String; AMsgBoxFlags: Longint):integer;
386var
387ADialog:TTaskDialog;
388begin
389Result :=0;
390if (AMsgBoxFlags>-1)and(Length(AMsg)>0) then
391begin
392ADialog :=TTaskDialog.Create(AOwner);
393ADialog.Caption :=Application.Title;
394ADialog.Text :=AMsg;
395ADialog.Flags :=[tfAllowDialogCancellation, tfPositionRelativeToWindow];
396
397if AWarningHint<>'' then
398begin
399ADialog.FooterIcon :=tdiWarning;
400ADialog.FooterText :=AWarningHint;
401end;
402
403if ((AMsgBoxFlags and MB_ICONEXCLAMATION)=MB_ICONEXCLAMATION)then
404begin
405ADialog.Title:='Уведомление';
406ADialog.CommonButtons := [];
407with TTaskDialogButtonItem(ADialog.Buttons.Add) do
408begin
409Caption := 'OK';
410ModalResult := mrOk;
411end;
412ADialog.MainIcon:=tdiWarning;
413if ADialog.Execute then
414begin
415Result:=ADialog.ModalResult;
416end;
417end
418else if (AMsgBoxFlags and MB_ICONQUESTION)=MB_ICONQUESTION then
419begin
420ADialog.Title:='Вопрос';
421ADialog.CommonButtons := [tcbYes, tcbNo];
422ADialog.MainIcon:=tdiQuestion;
423if ADialog.Execute then
424begin
425Result:=ADialog.ModalResult;
426end;
427end
428else if (AMsgBoxFlags and MB_ICONINFORMATION)=MB_ICONINFORMATION then
429begin
430ADialog.Title:='Информирование';
431ADialog.CommonButtons := [];
432with TTaskDialogButtonItem(ADialog.Buttons.Add) do
433begin
434Caption := 'OK';
435ModalResult := mrOk;
436end;
437ADialog.MainIcon:=tdiInformation;
438if ADialog.Execute then
439begin
440Result:=ADialog.ModalResult;
441end;
442end
443else if (AMsgBoxFlags and MB_ICONERROR)=MB_ICONERROR then
444begin
445ADialog.Title:='Исключение';
446ADialog.CommonButtons := [];
447with TTaskDialogButtonItem(ADialog.Buttons.Add) do
448begin
449Caption := 'OK';
450ModalResult := mrOk;
451end;
452ADialog.MainIcon:=tdiError;
453if ADialog.Execute then
454begin
455Result:=ADialog.ModalResult;
456end;
457end;
458ADialog.Free;
459end;
460end;
461
462function GetEnvVarValue(const VarName: string): string;
463begin
464{$IFDEF WINDOWS}
465Result := GetEnvironmentVariable(VarName);
466{$ELSE}
467Result := '';
468{$ENDIF}
469end;
470
471function SetSystemPathParamsToVar:Boolean;
472var
473reg :TRegistry;
474sName,
475sPath :String;
476i,i1,i2,
477iCountCicle :integer;
478Names:TStringList;
479begin
480Result :=False;
481SYSTEM_PATHVARS_INITED :=True;
482
483{$IFDEF WINDOWS}
484
485reg := TRegistry.Create;
486reg.Access := KEY_WOW64_64KEY or KEY_READ;
487Names := TStringList.Create;
488try
489
490sPath:=GetEnvVarValue('SystemDrive');
491SYSTEM_PATHVARS.AddPair('%SystemDrive%', sPath);
492
493reg.RootKey := HKEY_CURRENT_USER;
494
495if reg.OpenKeyReadOnly('Volatile Environment') then
496begin
497{
498reg.GetValueNames(Names);
499for i:=0 to Names.Count-1 do
500begin
501sName:=Names.Strings[i];
502SYSTEM_PATHVARS.AddPair('%'+sName+'%',reg.ReadString(sName));
503end;
504}
505SYSTEM_PATHVARS.AddPair('%APPDATA%',reg.ReadString('APPDATA')); // C:\Users\...\AppData\Roaming
506SYSTEM_PATHVARS.AddPair('%LOCALAPPDATA%',reg.ReadString('LOCALAPPDATA')); //C:\Users\...\AppData\Local
507SYSTEM_PATHVARS.AddPair('%USERDOMAIN%',reg.ReadString('USERDOMAIN'));
508SYSTEM_PATHVARS.AddPair('%USERNAME%',reg.ReadString('USERNAME'));
509SYSTEM_PATHVARS.AddPair('%USERPROFILE%',reg.ReadString('USERPROFILE'));
510SYSTEM_PATHVARS.AddPair('%HOMEDRIVE%',reg.ReadString('HOMEDRIVE'));
511
512reg.CloseKey;
513end
514else begin
515raise Exception.Create('Can`t read Windows registry "Volatile Environment" params');
516end;
517
518if reg.OpenKeyReadOnly('Environment') then
519begin
520
521SYSTEM_PATHVARS.AddPair('%TEMP%',reg.ReadString('TEMP'));
522SYSTEM_PATHVARS.AddPair('%TMP%',reg.ReadString('TMP'));
523
524reg.CloseKey;
525end
526else begin
527raise Exception.Create('Can`t read Windows registry "Environment" params');
528end;
529
530if reg.OpenKeyReadOnly('SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders') then
531begin
532SYSTEM_PATHVARS.AddPair('%USERDOWNLOADS%',reg.ReadString('{374DE290-123F-4565-9164-39C4925E467B}'));
533SYSTEM_PATHVARS.AddPair('%USERLOCALLOW%',reg.ReadString('{A520A1A4-1780-4FF6-BD18-167343C5AF16}'));
534reg.CloseKey;
535end
536else begin
537raise Exception.Create('Can`t read Windows registry "Shell Folders" params');
538end;
539
540reg.RootKey := HKEY_LOCAL_MACHINE;
541
542if reg.OpenKeyReadOnly('SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList') then
543begin
544SYSTEM_PATHVARS.AddPair('%ProgramData%',reg.ReadString('ProgramData'));
545SYSTEM_PATHVARS.AddPair('%ProfilesDirectory%',reg.ReadString('ProfilesDirectory'));
546SYSTEM_PATHVARS.AddPair('%Default%',reg.ReadString('Default'));
547SYSTEM_PATHVARS.AddPair('%Public%',reg.ReadString('Public'));
548
549reg.CloseKey;
550end
551else begin
552//raise Exception.Create('Can`t read Windows registry "HKEY_LOCAL_MACHINE" params');
553end;
554
555{Firebird}
556{}
557if reg.KeyExists('SOFTWARE\Firebird Project\Firebird Server\Instances') then
558begin
559if reg.OpenKeyReadOnly('SOFTWARE\Firebird Project\Firebird Server\Instances') then
560begin
561SYSTEM_PATHVARS.AddPair('%FirebirdProgramDirectory%',reg.ReadString('DefaultInstance'));
562reg.CloseKey;
563end;
564end;
565
566for i1:=0 to SYSTEM_PATHVARS.Count-1 do
567begin
568if UTF8Pos('%',SYSTEM_PATHVARS.ValueFromIndex[i1])>0 then
569begin
570iCountCicle :=SYSTEM_PATHVARS.Count;
571sPath :=SYSTEM_PATHVARS.ValueFromIndex[i1];
572while (iCountCicle>0) do
573begin
574
575for i2:=0 to SYSTEM_PATHVARS.Count-1 do
576begin
577sPath:=UTF8StringReplace(sPath,SYSTEM_PATHVARS.Names[i2],SYSTEM_PATHVARS.ValueFromIndex[i2],[rfIgnoreCase]);
578end;
579
580dec(iCountCicle);
581end;
582SYSTEM_PATHVARS.ValueFromIndex[i1]:=sPath;
583end;
584end;
585
586Result:=True;
587finally
588Names.Free;
589reg.Free;
590end;
591
592//Или так
593//FUnpackPath:=WinCPToUTF8(GetEnvironmentVariable(TEMPFOLDERWINDOWS)); //без %%
594
595{$ELSE}
596//SYSTEM_PATHVARS.AddPair('%APPDATA%',reg.ReadString('APPDATA'));
597//SYSTEM_PATHVARS.AddPair('%LOCALAPPDATA%',reg.ReadString('LOCALAPPDATA'));
598//SYSTEM_PATHVARS.AddPair('%USERDOMAIN%',reg.ReadString('USERDOMAIN'));
599SYSTEM_PATHVARS.AddPair('%USERNAME%',GetUserName(fpgetuid));
600//SYSTEM_PATHVARS.AddPair('%USERPROFILE%',reg.ReadString('USERPROFILE'));
601//SYSTEM_PATHVARS.AddPair('%HOMEDRIVE%',reg.ReadString('HOMEDRIVE'));
602SYSTEM_PATHVARS.AddPair('%TEMP%',GetTempDir(False));
603SYSTEM_PATHVARS.AddPair('%TMP%',GetTempDir(False));
604Result:=False;
605{$ENDIF}
606
607end;
608
609function SetProgramPathToVar:Boolean;
610var
611sPath :String;
612begin
613Result :=False;
614
615{$IFDEF WINDOWS}
616
617try
618sPath:=ExtractFilePath(Paramstr(0));
619sPath:=SysUtils.IncludeTrailingPathDelimiter(sPath);
620SYSTEM_PATHVARS.AddPair('%ProgramPath%', sPath);
621
622Result:=True;
623finally
624
625end;
626
627{$ELSE}
628Result:=False;
629{$ENDIF}
630
631end;
632
633function GetAbsolutSystemPath(var APath:String):Boolean;
634var
635iCountCicle, i :integer;
636sPath :String;
637begin
638Result :=False;
639
640{$IFDEF WINDOWS}
641
642if not SYSTEM_PATHVARS_INITED then
643begin
644if not SetSystemPathParamsToVar then
645Application.MessageBox(PChar('Не удалось получить параметры путей системы'), Pchar(Application.Title),MB_ICONERROR);
646end;
647
648if UTF8Pos('%',APath)>0 then
649begin
650iCountCicle :=SYSTEM_PATHVARS.Count;
651sPath :=APath;
652while (iCountCicle>0) do
653begin
654
655for i:=0 to SYSTEM_PATHVARS.Count-1 do
656begin
657sPath:=UTF8StringReplace(sPath,SYSTEM_PATHVARS.Names[i],SYSTEM_PATHVARS.ValueFromIndex[i],[rfIgnoreCase]);
658end;
659
660dec(iCountCicle);
661end;
662APath:=sPath;
663
664if UTF8Pos('%',APath)=0 then
665begin
666Result :=True;
667end;
668
669end
670else begin
671Result :=True;
672end;
673
674{$ELSE}
675Result :=False;;
676{$ENDIF}
677
678end;
679
680function GetGUID: String;
681var
682ID: TGUID;
683begin
684Result := '';
685if SysUtils.CreateGUID(ID) = S_OK then
686Result := GUIDToString(ID);
687{$IFDEF WINDOWS}
688//Windows
689//if ActiveX.CoCreateGuid(ID) = S_OK then
690// Result := GUIDToString(ID);
691{$ENDIF WINDOWS}
692{$IFDEF UNIX}
693
694{$ENDIF UNIX}
695end;
696
697{
698EXTENDED_NAME_FORMAT enumeration (secext.h)
699Minimum Windows 2000 Server
700Minimum Windows 2000 Professional
701}
702function GetUserNameExString(ANameFormat: DWORD): string;
703const
704NameUnknown = 0; // Unknown name type.
705NameFullyQualifiedDN = 1; // Fully qualified distinguished name
706NameSamCompatible = 2; // Windows NT® 4.0 account name
707NameDisplay = 3; // A "friendly" display name
708NameUniqueId = 6; // GUID string that the IIDFromString function returns
709NameCanonical = 7; // Complete canonical name
710NameUserPrincipal = 8; // User principal name
711NameCanonicalEx = 9;
712NameServicePrincipal = 10; // Generalized service principal name
713DNSDomainName = 11; // DNS domain name, plus the user name
714NameDnsDomain = 12; // The DNS domain name followed by a backward-slash and the SAM user name.
715NameGivenName = 13; // The first name or given name of the user.
716NameSurname = 14; // The last name or surname of the user.
717var
718Buf: array[0..256] of Char;
719BufSize: DWORD;
720begin
721Result := '';
722BufSize := SizeOf(Buf) div SizeOf(Buf[0]);
723if JwaWindows.GetUserNameEx(ANameFormat, @Buf[0], BufSize) then
724Result := Buf;
725end;
726
727function GetADUserData(var AOutData:TADUserData):Boolean;
728var
729rUser:TADUserData;
730begin
731Result:=False;
732try
733rUser.ADUser :=False;
734rUser.NameFullyQualifiedDN :=WinCPTOUTF8(GetUserNameExString(1));
735rUser.NameSamCompatible :=WinCPTOUTF8(GetUserNameExString(2));
736rUser.NameDisplay :=WinCPTOUTF8(GetUserNameExString(3));
737rUser.NameUniqueId :=WinCPTOUTF8(GetUserNameExString(6));
738rUser.NameCanonical :=WinCPTOUTF8(GetUserNameExString(7));
739rUser.NameUserPrincipal :=WinCPTOUTF8(GetUserNameExString(8));
740rUser.NameCanonicalEx :=WinCPTOUTF8(GetUserNameExString(9));
741rUser.NameServicePrincipal :=WinCPTOUTF8(GetUserNameExString(10));
742rUser.DNSDomainName :=WinCPTOUTF8(GetUserNameExString(11));
743rUser.NameDnsDomain :=WinCPTOUTF8(GetUserNameExString(12));
744rUser.NameGivenName :=WinCPTOUTF8(GetUserNameExString(13));
745rUser.NameSurname :=WinCPTOUTF8(GetUserNameExString(14));
746
747if (UTF8Length(rUser.NameUniqueId)>0)then
748begin
749rUser.ADUser :=True;
750end;
751AOutData :=rUser;
752Result :=True;
753finally
754
755end;
756end;
757
758//Определение имени пользователя
759{function GetUserName:String;
760var
761Buffer: array[0..MAX_PATH] of Char;
762sz:DWord;
763begin
764sz:=MAX_PATH-1;
765if windows.GetUserName(Buffer,sz)
766then begin
767if sz>0 then dec(sz);
768SetString(Result,Buffer,sz);
769end else begin
770Result:='';//inttostr(GetLastError);
771end;
772end;}
773
774function GetCurrentUserName : String;
775{$IFDEF WINDOWS}
776const
777MaxLen = 256;
778var
779Len: DWORD;
780WS: WideString;
781Res: windows.BOOL;
782{$ENDIF}
783begin
784Result := '';
785{$IFDEF UNIX}
786{$IF (DEFINED(LINUX)) OR (DEFINED(FREEBSD))}
787Result := SysToUtf8(GetUserName(fpgetuid)); //GetUsername in unit Users, fpgetuid in unit BaseUnix
788{$ELSE Linux/BSD}
789Result := GetEnvironmentVariableUtf8('USER');
790{$ENDIF UNIX}
791{$ELSE}
792{$IFDEF WINDOWS}
793Len := MaxLen;
794{$IFnDEF WINCE}
795if Win32MajorVersion <= 4 then
796begin
797SetLength(Result,MaxLen);
798Res := Windows.GetuserName(@Result[1], Len);
799if Res then
800begin
801SetLength(Result,Len-1);
802Result := SysToUtf8(Result);
803end
804else SetLength(Result,0);
805end
806else
807{$ENDIF NOT WINCE}
808begin
809SetLength(WS, MaxLen-1);
810Res := Windows.GetUserNameW(@WS[1], Len);
811if Res then
812begin
813SetLength(WS, Len - 1);
814Result := LazUTF8.UTF16ToUTF8(WS);
815end
816else SetLength(Result,0);
817end;
818{$ENDIF WINDOWS}
819{$ENDIF UNIX}
820end;
821
822function GetCurrentComputerName : String;
823{$IfDef WINDOWS}
824var
825l: DWORD;
826{$EndIf}
827begin
828{$IfDef LINUX}
829Result := GetHostName;
830{$EndIf}
831{$IfDef WINDOWS}
832l := 255;
833SetLength(Result, l);
834GetComputerName(PChar(Result), l);
835SetLength(Result, l);
836{$EndIf}
837{$IfDef appleOS}
838{$EndIf}
839end;
840
841function GetLocalHostname: string;
842var
843wVerReq: WORD;
844wsaData: TWSAData;
845h: PHostEnt;
846c: array[0..128] of char;
847begin
848wVerReq:=MAKEWORD(1, 1);
849WSAStartup(wVerReq, wsaData);
850{Получаем хост (имя) компа}
851GetHostName(@c, 128);
852h:=GetHostByName(@c);
853Result := h^.h_Name; //Host отображает хост(имя) компьютера
854end;
855
856function GetLocalIP: string;
857var
858wVerReq: WORD;
859wsaData: TWSAData;
860h: PHostEnt;
861c: array[0..128] of char;
862begin
863wVerReq:=MAKEWORD(1, 1);
864WSAStartup(wVerReq, wsaData);
865{Получаем хост (имя) компа}
866GetHostName(@c, 128);
867h:=GetHostByName(@c);
868{Достаем IP}
869Result := iNet_ntoa(PInAddr(h^.h_addr_list^)^);
870end;
871
872function StartApp(AFileName, AParams:String): Integer;
873var
874NewAppFileName,
875NewAppParams:string;
876begin
877try
878if FileExistsUTF8(AFileName) then
879begin
880NewAppFileName :=UTF8ToWinCP(AFileName);
881NewAppParams :='';
882
883if AParams<>'' then
884begin
885NewAppParams:=UTF8ToWinCP(AParams);
886end;
887{$IFDEF WINDOWS}
888ShellExecute(0, 'open', PChar(NewAppFileName),
889Pchar(NewAppParams), '', SW_SHOWNORMAL);
890Result:=1;
891{$ENDIF}
892{$IFDEF UNIX}
893AKey:='';
894AMsg:='Команда не адаптирована для unix.';
895OwnerApp.SystemLog(AKey, AMsg);
896{$ENDIF}
897end else begin
898Application.MessageBox(PChar('Не найден запускаемый файл'),Pchar(Application.Title),MB_ICONERROR);
899Result:=0;
900end;
901except
902on E: Exception do
903begin
904Application.MessageBox(PChar('Ошибка при попытке запуска программы'),Pchar(Application.Title),MB_ICONERROR);
905Result:=-1;
906end;
907end;
908end;
909
910function ChangeCurrentDirectory: boolean;
911var
912sBuffer:Pchar;
913sExeFilePath:String;
914begin
915Result:=False;
916{$IFDEF WINDOWS}
917sExeFilePath :=ParamStr(0);
918sExeFilePath :=ExtractFilePath(sExeFilePath);
919sBuffer :=PChar(sExeFilePath);
920if SetCurrentDirectory(sBuffer) then
921begin
922Result:=True;
923end;
924{
925if GetCurrentDirectory(255,sBuffer)>0 then
926sBuffer:=Pchar(WinCPToUTF8(sBuffer));
927FThisApp.SystemLog(AKey, format('CurrentDirectory %s',[sBuffer]));
928}
929{$ENDIF}
930end;
931
932function GetEXEVersionData(const FileName: string; var OutData:TEXEVersionData): Boolean;
933type
934PLandCodepage = ^TLandCodepage;
935TLandCodepage = record
936wLanguage,
937wCodePage: word;
938end;
939var
940dummy,
941len: cardinal;
942buf, pntr: pointer;
943lang: string;
944begin
945Result := False;
946try
947len := GetFileVersionInfoSize(PChar(FileName), dummy);
948except
949len :=0;
950end;
951
952if len>0 then
953begin
954//if len = 0 then
955// RaiseLastOSError;
956GetMem(buf, len);
957try
958if not GetFileVersionInfo(PChar(FileName), 0, len, buf) then
959RaiseLastOSError;
960
961if not VerQueryValue(buf, '\VarFileInfo\Translation\', pntr, len) then
962RaiseLastOSError;
963
964lang := Format('%.4x%.4x', [PLandCodepage(pntr)^.wLanguage, PLandCodepage(pntr)^.wCodePage]);
965
966if VerQueryValue(buf, PChar('\StringFileInfo\' + lang + '\CompanyName'), pntr, len){ and (@len <> nil)} then
967OutData.CompanyName := PChar(pntr);
968if VerQueryValue(buf, PChar('\StringFileInfo\' + lang + '\FileDescription'), pntr, len){ and (@len <> nil)} then
969OutData.FileDescription := PChar(pntr);
970if VerQueryValue(buf, PChar('\StringFileInfo\' + lang + '\FileVersion'), pntr, len){ and (@len <> nil)} then
971OutData.FileVersion := PChar(pntr);
972if VerQueryValue(buf, PChar('\StringFileInfo\' + lang + '\InternalName'), pntr, len){ and (@len <> nil)} then
973OutData.InternalName := PChar(pntr);
974if VerQueryValue(buf, PChar('\StringFileInfo\' + lang + '\LegalCopyright'), pntr, len){ and (@len <> nil)} then
975OutData.LegalCopyright := PChar(pntr);
976if VerQueryValue(buf, PChar('\StringFileInfo\' + lang + '\LegalTrademarks'), pntr, len){ and (@len <> nil)} then
977OutData.LegalTrademarks := PChar(pntr);
978if VerQueryValue(buf, PChar('\StringFileInfo\' + lang + '\OriginalFileName'), pntr, len){ and (@len <> nil)} then
979OutData.OriginalFileName := PChar(pntr);
980if VerQueryValue(buf, PChar('\StringFileInfo\' + lang + '\ProductName'), pntr, len){ and (@len <> nil)} then
981OutData.ProductName := PChar(pntr);
982if VerQueryValue(buf, PChar('\StringFileInfo\' + lang + '\ProductVersion'), pntr, len){ and (@len <> nil)} then
983OutData.ProductVersion := PChar(pntr);
984if VerQueryValue(buf, PChar('\StringFileInfo\' + lang + '\Comments'), pntr, len){ and (@len <> nil)} then
985OutData.Comments := PChar(pntr);
986if VerQueryValue(buf, PChar('\StringFileInfo\' + lang + '\PrivateBuild'), pntr, len){ and (@len <> nil)} then
987OutData.PrivateBuild := PChar(pntr);
988if VerQueryValue(buf, PChar('\StringFileInfo\' + lang + '\SpecialBuild'), pntr, len){ and (@len <> nil)} then
989OutData.SpecialBuild := PChar(pntr);
990
991Result := True;
992finally
993FreeMem(buf);
994end;
995
996end;
997end;
998
999//look ForceDirectory
1000{
1001function CreateDirEx(Dir: string): Boolean;
1002var
1003I, L: Integer;
1004CurDir: string;
1005begin
1006Result := False;
1007CurDir :='';
1008Dir :=UTF8ToSys(Dir);
1009if SysUtils.ExcludeTrailingPathDelimiter(Dir) <> '' then
1010begin
1011Dir := SysUtils.IncludeTrailingPathDelimiter(Dir);
1012L := Length(Dir);
1013for I := 1 to L do
1014begin
1015CurDir := CurDir + Copy(Dir,I,1);
1016if Copy(Dir,I,1) = SysUtils.PathDelim then
1017begin
1018if not DirectoryExists(CurDir) then
1019if not CreateDir(CurDir) then
1020Exit;
1021end;
1022end;
1023if DirectoryExists(Dir) then
1024Result := True;
1025end;
1026end;
1027}
1028function PathExists(APath: String; ACreate: Boolean): boolean;
1029var
1030sPath:String;
1031begin
1032Result := False;
1033if Length(APath)>0 then
1034begin
1035sPath :=IncludeTrailingPathDelimiter(APath);
1036if (not DirPathExists(sPath))and(ACreate) then
1037begin
1038if ForceDirectory(sPath) then
1039Result := True;
1040end
1041else begin
1042Result := True;
1043end;
1044end;
1045end;
1046
1047{ TNMDialogFormActions }
1048
1049procedure TNMDialogFormActions.ButtonClose(Sender: TObject);
1050var
1051TmpParent: TWinControl;
1052begin
1053if (Sender is TButton) then
1054begin
1055TmpParent:=TButton(Sender).Parent;
1056TmpParent:=TmpParent.Parent;
1057TForm(TmpParent).Close;
1058end;
1059end;
1060
1061procedure TNMDialogFormActions.FormClose(Sender: TObject;
1062var CloseAction: TCloseAction);
1063begin
1064CloseAction:=caFree;
1065end;
1066
1067Initialization
1068SYSTEM_PATHVARS_INITED :=False;
1069SYSTEM_PATHVARS :=TStringList.Create;
1070SYSTEM_PATHVARS.Delimiter :='=';
1071SetProgramPathToVar;
1072SetSystemPathParamsToVar;
1073NMDialogFormActions :=TNMDialogFormActions.Create;
1074
1075finalization
1076NMDialogFormActions.Free;
1077SYSTEM_PATHVARS.Free;
1078end.