forked from rejetto/hfs2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utillib.pas
3238 lines (2958 loc) · 86.1 KB
/
utillib.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{
Copyright (C) 2002-2020 Massimo Melina (www.rejetto.com)
This file is part of HFS ~ HTTP File Server.
HFS is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
HFS is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with HFS; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
}
{$INCLUDE defs.inc }
unit utilLib;
interface
uses
IOUtils, main, hslib, regexpr, types, windows, graphics, dialogs, registry, classes, dateUtils, Vcl.Imaging.GIFImg,
shlobj, shellapi, activex, comobj, strutils, forms, stdctrls, controls, psAPI, menus, math,
longinputDlg, OverbyteIcsWSocket, OverbyteIcshttpProt, comCtrls, iniFiles, richedit, sysutils, classesLib{, fastmm4};
const
ILLEGAL_FILE_CHARS = [#0..#31,'/','\',':','?','*','"','<','>','|'];
DOW2STR: array [1..7] of string=( 'Sun','Mon','Tue','Wed','Thu','Fri','Sat' );
MONTH2STR: array [1..12] of string = ( 'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec' );
PTR1: Tobject = ptr(1);
var
GMToffset: integer; // in minutes
inputQueryLongdlg: TlonginputFrm;
winVersion: (WV_LOWER, WV_2000, WV_VISTA, WV_SEVEN, WV_HIGHER);
type
TcharSet = set of char;
TreCB = procedure(re:TregExpr; var res:string; data:pointer);
PstringDynArray = ^TstringDynArray;
TnameExistsFun = function(user:string):boolean;
procedure doNothing(); inline; // useful for readability
function httpsCanWork():boolean;
function accountExists(user:string; evenGroups:boolean=FALSE):boolean;
function getAccount(user:string; evenGroups:boolean=FALSE):Paccount;
function nodeToFile(n:TtreeNode):Tfile;
procedure fixFontFor(frm:Tform);
function hostFromURL(s:string):string;
function hostToIP(name: string):string;
function allocatedMemory():int64;
function stringToGif(s:ansistring; gif:TgifImage=NIL):TgifImage;
function maybeUnixTime(t:Tdatetime):Tdatetime;
function filetimeToDatetime(ft:TFileTime):Tdatetime;
function localToGMT(d:Tdatetime):Tdatetime;
function onlyExistentAccounts(a:TstringDynArray):TstringDynArray;
procedure onlyForExperts(controls:array of Tcontrol);
function createAccountOnTheFly():Paccount;
function newMenuSeparator(lbl:string=''):Tmenuitem;
function accountIcon(isEnabled, isGroup:boolean):integer; overload;
function accountIcon(a:Paccount):integer; overload;
function evalFormula(s:string):real;
function boolOnce(var b:boolean):boolean;
procedure drawCentered(cnv:Tcanvas; r:Trect; text:string);
function minmax(min, max, v:integer):integer;
function isLocalIP(ip:string):boolean;
function clearAndReturn(var v:string):string;
function swapMem(var src,dest; count:dword; cond:boolean=TRUE):boolean;
function pid2file(pid:integer):string;
function port2pid(port:string):integer;
function holdingKey(key:integer):boolean;
function blend(from,to_:Tcolor; perc:real):Tcolor;
function isNT():boolean;
function setClip(s:string):boolean;
function eos(s:Tstream):boolean;
function safeDiv(a,b:real; default:real=0):real; overload;
function safeDiv(a,b:int64; default:int64=0):int64; overload;
function safeMod(a,b:int64; default:int64=0):int64;
function smartsize(size:int64):string;
function httpGet(url:string; from:int64=0; size:int64=-1):string;
function httpGetFile(url, filename:string; tryTimes:integer=1; notify:TdocDataEvent=NIL):boolean;
function httpFileSize(url:string):int64;
function getPossibleAddresses():TstringDynArray;
function whatStatusPanel(statusbar:Tstatusbar; x:integer):integer;
function getExternalAddress(var res:string; provider:Pstring=NIL):boolean;
function checkAddressSyntax(address:string; mask:boolean=TRUE):boolean;
function inputQueryLong(const caption, msg:string; var value:string; ofs:integer=0):boolean;
procedure purgeVFSaccounts();
function exec(cmd:string; pars:string=''; showCmd:integer=SW_SHOW):boolean;
function execNew(cmd:string):boolean;
function captureExec(DosApp : string; out output:string; out exitcode:cardinal; timeout:real=0):boolean;
function openURL(url:string):boolean;
function getRes(name:pchar; typ:string='TEXT'):string;
function bmpToHico(bitmap:Tbitmap):hicon;
function compare_(i1,i2:double):integer; overload;
function compare_(i1,i2:int64):integer; overload;
function compare_(i1,i2:integer):integer; overload;
function msgDlg(msg:string; code:integer=0; title:string=''):integer;
function if_(v:boolean; v1:string; v2:string=''):string; overload; inline;
function if_(v:boolean; v1:ansistring; v2:ansistring=''):ansistring; overload; inline;
function if_(v:boolean; v1:int64; v2:int64=0):int64; overload; inline;
function if_(v:boolean; v1:integer; v2:integer=0):integer; overload; inline;
function if_(v:boolean; v1:Tobject; v2:Tobject=NIL):Tobject; overload; inline;
function if_(v:boolean; v1:boolean; v2:boolean=FALSE):boolean; overload; inline;
// file
function getEtag(filename:string):string;
function getDrive(fn:string):string;
function diskSpaceAt(path:string):int64;
function deltree(path:string):boolean;
function newMtime(fn:string; var previous:Tdatetime):boolean;
function dirCrossing(s:string):boolean;
function forceDirectory(path:string):boolean;
function moveToBin(fn:string; force:boolean=FALSE):boolean; overload;
function moveToBin(files:TstringDynArray; force:boolean=FALSE):boolean; overload;
function uri2disk(url:string; parent:Tfile=NIL; resolveLnk:boolean=TRUE):string;
function uri2diskMaybe(path:string; parent:Tfile=NIL; resolveLnk:boolean=TRUE):string;
function freeIfTemp(var f:Tfile):boolean; inline;
function isAbsolutePath(path:string):boolean;
function getTempDir():string;
function createShellLink(linkFN:WideString; destFN:string):boolean;
function readShellLink(linkFN:WideString):string;
function getShellFolder(id:string):string;
function getTempFilename():string;
function saveTempFile(data:ansistring):string; overload;
function saveTempFile(data:string):string; overload;
function fileOrDirExists(fn:string):boolean;
function sizeOfFile(fn:string):int64; overload;
function sizeOfFile(fh:Thandle):int64; overload;
function loadFile(fn:string; from:int64=0; size:int64=-1):ansistring;
function loadTextFile(fn:string):string;
function saveTextFile(fn:string; text:string; append:boolean=FALSE):boolean;
function saveFile(fn:string; data:ansistring; append:boolean=FALSE):boolean; overload;
function saveFile(var f:file; data:ansistring):boolean; overload;
function moveFile(src, dst:string; op:UINT=FO_MOVE):boolean;
function copyFile(src, dst:string):boolean;
function resolveLnk(fn:string):string;
function validFilename(s:string):boolean;
function validFilepath(fn:string; acceptUnits:boolean=TRUE):boolean;
function match(mask, txt:pchar; fullMatch:boolean=TRUE; charsNotWildcard:Tcharset=[]):integer;
function filematch(mask, fn:string):boolean;
function appendFile(fn:string; data:ansistring):boolean;
function appendTextFile(fn:string; text:string):boolean;
function getFilename(var f:file):string;
function filenameToDriveByte(fn:string):byte;
function selectFile(var fn:string; title:string=''; filter:string=''; options:TOpenOptions=[]):boolean;
function selectFiles(caption:string; var files:TStringDynArray):boolean;
function selectFolder(caption:string; var folder:string):boolean;
function selectFileOrFolder(caption:string; var fileOrFolder:string):boolean;
function isExtension(filename, ext:string):boolean;
function getMtimeUTC(filename:string):Tdatetime;
function getMtime(filename:string):Tdatetime;
// registry
function loadregistry(key,value:string; root:HKEY=0):string;
function saveregistry(key,value,data:string; root:HKEY=0):boolean;
function deleteRegistry(key,value:string; root:HKEY=0):boolean; overload;
function deleteRegistry(key:string; root:HKEY=0):boolean; overload;
// strings array
function split(separator, s:string; nonQuoted:boolean=FALSE):TStringDynArray;
function join(separator:string; ss:TstringDynArray):string;
function addUniqueString(s:string; var ss:TStringDynArray):boolean;
function addString(s:string; var ss:TStringDynArray):integer;
function replaceString(var ss:TStringDynArray; old, new:string):integer;
function popString(var ss:TstringDynArray):string;
procedure insertString(s:string; idx:integer; var ss:TStringDynArray);
function removeString(var a:TStringDynArray; idx:integer; l:integer=1):boolean; overload;
function removeString(s:string; var a:TStringDynArray; onlyOnce:boolean=TRUE; ci:boolean=TRUE; keepOrder:boolean=TRUE):boolean; overload;
procedure removeStrings(find:string; var a:TStringDynArray);
procedure toggleString(s:string; var ss:TStringDynArray);
function onlyString(s:string; ss:TStringDynArray):boolean;
function addArray(var dst:TstringDynArray; src:array of string; where:integer=-1; srcOfs:integer=0; srcLn:integer=-1):integer;
function removeArray(var src:TstringDynArray; toRemove:array of string):integer;
function addUniqueArray(var a:TstringDynArray; b:array of string):integer;
procedure uniqueStrings(var a:TstringDynArray; ci:Boolean=TRUE);
function idxOf(s:string; a:array of string; isSorted:boolean=FALSE):integer;
function stringExists(s:string; a:array of string; isSorted:boolean=FALSE):boolean;
function listToArray(l:Tstrings):TstringDynArray;
function arrayToList(a:TStringDynArray; list:TstringList=NIL):TstringList;
function sortArray(a:TStringDynArray):TStringDynArray;
// convert
function boolToPtr(b:boolean):pointer;
function strToCharset(s:string):Tcharset;
function ipToInt(ip:string):dword;
function rectToStr(r:Trect):string;
function strToRect(s:string):Trect;
function dt_(s:ansistring):Tdatetime;
function int_(s:ansistring):integer;
function str_(i:integer):ansistring; overload;
function str_(fa:TfileAttributes):ansistring; overload;
function str_(t:Tdatetime):ansistring; overload;
function str_(b:boolean):ansistring; overload;
function strToUInt(s:string):integer;
function elapsedToStr(t:Tdatetime):string;
function dateToHTTP(gmtTime:Tdatetime):string; overload;
function dateToHTTP(filename:string):string; overload;
function toSA(a:array of string):TstringDynArray; // this is just to have a way to typecast
function stringToColorEx(s:string; default:Tcolor=clNone):Tcolor;
// misc string
procedure excludeTrailingString(var s:string; ss:string);
function findEOL(s:string; ofs:integer=1; included:boolean=TRUE):integer;
function getUniqueName(start:string; exists:TnameExistsFun):string;
function getStr(from,to_:pchar):string;
function TLV(t:integer; s:string):ansistring; overload;
function TLV(t:integer; data:ansistring):ansistring; overload;
function TLV_NOT_EMPTY(t:integer; s:string):ansistring; overload;
function TLV_NOT_EMPTY(t:integer; data:ansistring):ansistring;overload;
function getCRC(data:ansistring):integer;
function dotted(i:int64):string;
function xtpl(src:string; table:array of string):string; overload;
function validUsername(s:string; acceptEmpty:boolean=FALSE):boolean;
function anycharIn(chars, s:string):boolean; overload;
function anycharIn(chars:Tcharset; s:string):boolean; overload;
function int0(i,digits:integer):string;
function addressmatch(mask, address:string):boolean;
function getTill(ss, s:string; included:boolean=FALSE):string; overload;
function getTill(i:integer; s:string):string; overload;
function singleLine(s:string):boolean;
function poss(chars:TcharSet; s:string; ofs:integer=1):integer;
function jsEncode(s, chars:string):string;
function nonEmptyConcat(pre,s:string; post:string=''):string;
function first(a,b:integer):integer; overload;
function first(a,b:double):double; overload;
function first(a,b:pointer):pointer; overload;
function first(a,b:string):string; overload;
function first(a,b:ansistring):ansistring; overload;
function first(a:array of string):string; overload;
function stripChars(s:string; cs:Tcharset; invert:boolean=FALSE):string;
function isOnlyDigits(s:string):boolean;
function strAt(s, ss:string; at:integer):boolean; inline;
function substr(s:string; start:integer; upTo:integer=0):string; inline; overload;
function substr(s:string; after:string):string; overload;
function reduceSpaces(s:string; replacement:string=' '; spaces:TcharSet=[]):string;
function replace(var s:string; ss:string; start,upTo:integer):integer;
function countSubstr(ss:string; s:string):integer;
function trim2(s:string; chars:Tcharset):string;
procedure urlToStrings(s:ansistring; sl:Tstrings);
function reCB(expr, subj:string; cb:TreCB; data:pointer=NIL):string;
function reMatch(s, exp:string; mods:string='m'; ofs:integer=1; subexp:PstringDynArray=NIL):integer;
function reReplace(subj, exp, repl:string; mods:string='m'):string;
function reGet(s, exp:string; subexpIdx:integer=1; mods:string='!mi'; ofs:integer=1):string;
function getSectionAt(p:pchar; out name:string):boolean;
function isSectionAt(p:pchar):boolean;
function dequote(s:string; quoteChars:TcharSet=['"']):string;
function quoteIfAnyChar(badChars, s:string; quote:string='"'; unquote:string='"'):string;
function getKeyFromString(s:string; key:string; def:string=''):string;
function setKeyInString(s:string; key:string; val:string=''):string;
function getFirstChar(s:string):char;
function escapeNL(s:string):string;
function unescapeNL(s:string):string;
function htmlEncode(s:string):string;
procedure enforceNUL(var s:string);
function strSHA256(s:string):string;
function strSHA1(s:string):string;
function strMD5(s:string):string;
function strToOem(s:string):ansistring;
function strToBytes(s:ansistring):Tbytes;
implementation
uses
clipbrd, JclNTFS, JclWin32, parserLib, newuserpassDlg, winsock, System.Hash, ansistrings;
var
ipToInt_cache: ThashedStringList;
onlyDotsRE: TRegExpr;
function strSHA256(s:string):string;
begin result:=THashSHA2.GetHashString(UTF8encode(s)) end;
function strSHA1(s:string):string;
begin result:=THashSHA1.GetHashString(UTF8encode(s)) end;
function strMD5(s:string):string;
begin result:=THashMD5.GetHashString(UTF8encode(s)) end;
function strToOem(s:string):ansistring;
begin
setLength(result, length(s));
CharToOemBuff(pWideChar(s), pAnsiChar(result), length(s));
end; // strToOem
// method TregExpr.ReplaceEx does the same thing, but doesn't allow the extra data field (sometimes necessary).
// Moreover, here i use the TfastStringAppend that will give us good performance with many replacements.
function reCB(expr, subj:string; cb:TreCB; data:pointer=NIL):string;
var
r: string;
last: integer;
re: TRegExpr;
s: TfastStringAppend;
begin
re:=TRegExpr.create;
s:=TfastStringAppend.create;
try
re.modifierI:=TRUE;
re.ModifierS:=FALSE;
re.expression:=expr;
re.compile();
last:=1;
if re.exec(subj) then
repeat
r:=re.match[0];
cb(re, r, data);
if re.MatchPos[0] > 1 then
s.append(substr(subj, last, re.matchPos[0]-1)); // we must IF because 0 is the end of string for substr()
s.append(r);
last:=re.matchPos[0]+re.matchLen[0];
until not re.execNext();
s.append(substr(subj, last));
result:=s.get();
finally
re.free;
s.free;
end
end; // reCB
// this is meant to detect junctions, symbolic links, volume mount points
function isJunction(path:string):boolean; inline;
var
attr: DWORD;
begin
attr:=getFileAttributes(PChar(path));
// don't you dare to convert the <>0 in a boolean typecast! my TurboDelphi (2006) generates the wrong assembly :-(
result:=(attr <> DWORD(-1)) and (attr and FILE_ATTRIBUTE_REPARSE_POINT <> 0)
end;
// the file may not be a junction itself, but we may have a junction at some point in the path
function hasJunction(fn:string):string;
var
i: integer;
begin
i:=length(fn);
while i > 0 do
begin
result:=copy(fn,1,i);
if isJunction(result) then
exit;
while (i > 0) and not charInSet(fn[i],['\','/']) do dec(i);
dec(i);
end;
result:='';
end; // hasJunction
// this is a fixed version of the one contained in JclNTFS.pas
function NtfsGetJunctionPointDestination(const Source: string; var Destination: widestring): Boolean;
var
Handle: THandle;
ReparseData: record
case Boolean of
False: (Reparse: TReparseDataBuffer;);
True: (Buffer: array [0..MAXIMUM_REPARSE_DATA_BUFFER_SIZE] of Char;);
end;
BytesReturned: DWORD;
begin
Result := False;
if not NtfsFileHasReparsePoint(Source) then exit;
handle := CreateFile(PChar(Source), GENERIC_READ, 0, nil, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS or FILE_FLAG_OPEN_REPARSE_POINT, 0);
if handle = INVALID_HANDLE_VALUE then exit;
try
BytesReturned := 0;
if not DeviceIoControl(Handle, FSCTL_GET_REPARSE_POINT, nil, 0, @ReparseData, MAXIMUM_REPARSE_DATA_BUFFER_SIZE, BytesReturned, nil) then exit;
if BytesReturned < DWORD(ReparseData.Reparse.SubstituteNameLength + SizeOf(WideChar)) then exit;
SetLength(Destination, (ReparseData.Reparse.SubstituteNameLength div SizeOf(WideChar)));
Move(ReparseData.Reparse.PathBuffer[0], Destination[1], ReparseData.Reparse.SubstituteNameLength);
Result := True;
finally CloseHandle(Handle) end
end; // NtfsGetJunctionPointDestination
function getDrive(fn:string):string;
var
i: integer;
ws: widestring;
begin
result:=fn;
repeat
fn:=hasJunction(result);
if fn = '' then break;
if not NtfsGetJunctionPointDestination(fn, ws) then
break; // at worst we hope the drive is the same
result:=WideCharToString(@ws[1]);
// sometimes we get a unicode result
i:=length(result);
if (i > 3) and (result[2] = #0) then
begin
break;
result:=wideCharToString(@result[1]);
setLength(result, i-1);
end;
// remove some trailing null chars
result:=trim(result);
// we don't like this form, remove useless chars
if reMatch(result, '^\\\?\?\\.:', '!') > 0 then
delete(result, 1,4);
until false;
result:=extractFileDrive(result);
end; // getDrive
function moveToBin(fn:string; force:boolean=FALSE):boolean; overload;
begin result:=moveToBin(toSA(fn), force) end;
function moveToBin(files:TstringDynArray; force:boolean=FALSE):boolean; overload;
var
fo: TSHFileOpStruct;
i: integer;
fn, test, list: string;
begin
result:=FALSE;
// the list is null-separated. A double-null will mark the end of the list, but delphi adds an extra hidden null in every string.
list:='';
try
for i:=0 to length(files)-1 do
begin
fn:=expandFileName(files[i]); // if we don't specify a full path, the bin won't be used, and the file will be just deleted
test:=fn;
if (reMatch(fn, '[*?]', '!')>0) then
test:=ExtractFilePath(test);
// this system call doesn't work on linked files. Moreover, it hangs the process for a while, so we try to detect them, to abort.
if not fileOrDirExists(test) or (hasJunction(test) > '') then continue;
list:=list+fn+#0;
end;
if list = '' then exit;
try
fillChar(fo, sizeOf(fo), 0);
fo.wFunc:=FO_DELETE;
fo.pFrom:=pchar(list);
fo.fFlags:=FOF_ALLOWUNDO or FOF_NOCONFIRMATION or FOF_NOERRORUI or FOF_SILENT;
result:=SHFileOperation(fo) = 0;
except result:=FALSE end;
finally
if not result and force then
begin
// enter the rude
result:=TRUE;
for i:=0 to length(files)-1 do
result:=result and deltree(files[i]);
end;
end;
end; // moveToBin
function moveFile(src, dst:string; op:UINT=FO_MOVE):boolean;
var
fo: TSHFileOpStruct;
begin
try
fillChar(fo, sizeOf(fo), 0);
fo.wFunc:=op;
fo.pFrom:=pchar(src+#0);
fo.pTo:=pchar(dst+#0);
fo.fFlags:=FOF_ALLOWUNDO + FOF_NOCONFIRMATION + FOF_NOERRORUI + FOF_SILENT + FOF_NOCONFIRMMKDIR;
result:=SHFileOperation(fo) = 0;
except result:=FALSE end;
end; // movefile
function copyFile(src, dst:string):boolean;
begin result:=movefile(src, dst, FO_COPY) end;
var
reTempCache, reFixedCache: THashedStringList;
function reCache(exp:string; mods:string='m'):TregExpr;
const
CACHE_MAX = 100;
var
i: integer;
cache: THashedStringList;
temporary: boolean;
key: string;
begin
// this is a temporary cache: older things get deleted. order: first is older, last is newer.
if reTempCache = NIL then
reTempCache:=THashedStringList.create();
// this is a permanent cache: things are never deleted (while the process is alive)
if reFixedCache = NIL then
reFixedCache:=THashedStringList.create();
// is it temporary or not?
i:=pos('!', mods);
temporary:= i=0;
Tobject(cache):=if_(temporary, reTempCache, reFixedCache);
delete(mods, i, 1);
// access the cache
key:=mods+#255+exp;
i:=cache.indexOf(key);
if i >= 0 then
begin
result:=cache.objects[i] as TregExpr;
if temporary then
cache.move(i, cache.count-1); // just requested, refresh position
end
else
begin
// cache fault, create new object
result:=TRegExpr.Create;
cache.addObject(key, result);
if temporary and (cache.count > CACHE_MAX) then
// delete older ones
for i:=1 to CACHE_MAX div 10 do
try
cache.objects[0].free;
cache.delete(0);
except end;
result.modifierS:=FALSE;
result.modifierStr:=mods;
result.expression:=exp;
result.compile();
end;
end;//reCache
function reMatch(s, exp:string; mods:string='m'; ofs:integer=1; subexp:PstringDynArray=NIL):integer;
var
i: integer;
re: TRegExpr;
begin
result:=0;
re:=reCache(exp,mods);
if assigned(subexp) then
subexp^:=NIL;
// do the job
try
re.inputString:=s;
if not re.execPos(ofs) then exit;
result:=re.matchPos[0];
if subexp = NIL then exit;
i:=re.subExprMatchCount;
setLength(subexp^, i+1); // it does include also the whole match, with index zero
for i:=0 to i do
subexp^[i]:=re.match[i]
except end;
end; // reMatch
function reGet(s, exp:string; subexpIdx:integer=1; mods:string='!mi'; ofs:integer=1):string;
var
se: TstringDynArray;
begin
if reMatch(s, exp, mods, ofs, @se) > 0 then
result:=se[subexpIdx]
else
result:='';
end; // reGet
function reReplace(subj, exp, repl:string; mods:string='m'):string;
var
re: TRegExpr;
begin
re:=reCache(exp,mods);
result:=re.replace(subj, repl, TRUE);
end; // reReplace
// converts from integer to string[4]
function str_(i:integer):ansistring; overload;
begin
setlength(result, 4);
move(i, result[1], 4);
end; // str_
// converts from boolean to string[1]
function str_(b:boolean):ansistring; overload;
begin result:=ansichar(b) end;
// converts from TfileAttributes to string[4]
function str_(fa:TfileAttributes):ansistring; overload;
begin result:=str_(integer(fa)) end;
// converts from Tdatetime to string[8]
function str_(t:Tdatetime):ansistring; overload;
begin
setlength(result, 8);
move(t, result[1], 8);
end; // str_
// converts from string[4] to integer
function int_(s:ansistring):integer;
begin result:=Pinteger(@s[1])^ end;
// converts from string[8] to datetime
function dt_(s:ansistring):Tdatetime;
begin result:=Pdatetime(@s[1])^ end;
function strToUInt(s:string):integer;
begin
s:=trim(s);
if s='' then result:=0
else result:=strToInt(s);
if result < 0 then
raise Exception.Create('strToUInt: Signed value not accepted');
end; // strToUInt
function split(separator, s:string; nonQuoted:boolean=FALSE):TStringDynArray;
var
i, j, n, l: integer;
begin
l:=length(s);
result:=NIL;
if l = 0 then exit;
i:=1;
n:=0;
repeat
if length(result) = n then
setLength(result, n+50);
if nonQuoted then
j:=nonQuotedPos(separator, s, i)
else
j:=posEx(separator, s, i);
if j = 0 then
j:=l+1;
if i < j then
result[n]:=substr(s, i, j-1);
i:=j+length(separator);
inc(n);
until j > l;
setLength(result, n);
end; // split
function join(separator:string; ss:TstringDynArray):string;
var
i:integer;
begin
result:='';
if length(ss) = 0 then exit;
result:=ss[0];
for i:=1 to length(ss)-1 do
result:=result+separator+ss[i];
end; // join
procedure toggleString(s:string; var ss:TStringDynArray);
var
i: integer;
begin
i:=idxOf(s, ss);
if i < 0 then addString(s, ss)
else removeString(ss, i);
end; // toggleString
procedure uniqueStrings(var a:TstringDynArray; ci:Boolean=TRUE);
var
i, j: integer;
begin
for i:=length(a)-1 downto 1 do
for j:=i-1 downto 0 do
if ci and SameText(a[i], a[j])
or not ci and (a[i] = a[j]) then
begin
removeString(a, i);
break;
end;
end; // uniqueStrings
// remove all instances of the specified string
procedure removeStrings(find:string; var a:TStringDynArray);
var
i, l: integer;
begin
repeat
i:=idxOf(find,a);
if i < 0 then break;
l:=1;
while (i+l < length(a)) and (ansiCompareText(a[i+l], find) = 0) do inc(l);
removeString(a, i, l);
until false;
end; // removeStrings
function removeArray(var src:TstringDynArray; toRemove:array of string):integer;
var
i, l, ofs: integer;
b: boolean;
begin
l:=length(src);
i:=0;
ofs:=0;
while i+ofs < l do
begin
b:=stringExists(src[i+ofs], toRemove);
if b then inc(ofs);
if i+ofs > l then break;
if ofs > 0 then src[i]:=src[i+ofs];
if not b then inc(i);
end;
setLength(src, l-ofs);
result:=ofs;
end; // removeArray
function popString(var ss:TstringDynArray):string;
begin
result:='';
if ss = NIL then exit;
result:=ss[0];
removeString(ss, 0);
end; // popString
function addString(s:string; var ss:TStringDynArray):integer;
begin
result:=length(ss);
addArray(ss, [s], result)
end; // addString
function replaceString(var ss:TStringDynArray; old, new:string):integer;
var
i: integer;
begin
result:=0;
repeat
i:=idxOf(old, ss);
if i < 0 then exit;
inc(result);
ss[i]:=new;
until false;
end; // replaceString
function onlyString(s:string; ss:TStringDynArray):boolean;
// we are case insensitive, just like other functions in this set
begin result:=(length(ss) = 1) and sameText(ss[0], s) end;
function addUniqueString(s:string; var ss:TStringDynArray):boolean;
begin
result:=idxof(s, ss) < 0;
if result then addString(s, ss)
end; // addUniqueString
procedure insertstring(s:string; idx:integer; var ss:TStringDynArray);
begin addArray(ss, [s], idx) end;
function removestring(var a:TStringDynArray; idx:integer; l:integer=1):boolean;
begin
result:=FALSE;
if (idx<0) or (idx >= length(a)) then exit;
result:=TRUE;
while idx+l < length(a) do
begin
a[idx]:=a[idx+l];
inc(idx);
end;
setLength(a, idx);
end; // removestring
function removeString(s:string; var a:TStringDynArray; onlyOnce:boolean=TRUE; ci:boolean=TRUE; keepOrder:boolean=TRUE):boolean; overload;
var i, lessen:integer;
begin
result:=FALSE;
if a = NIL then
exit;
lessen:=0;
try
for i:=length(a)-1 to 0 do
if ci and sameText(a[i], s)
or not ci and (a[i]=s) then
begin
result:=TRUE;
if keepOrder then
removeString(a, i)
else
begin
inc(lessen);
a[i]:=a[length(a)-lessen];
end;
if onlyOnce then
exit;
end;
finally
if lessen > 0 then
setLength(a, length(a)-lessen);
end;
end;
function dotted(i:int64):string;
begin
result:=intToStr(i);
i:=length(result)-2;
while i > 1 do
begin
insert(FormatSettings.ThousandSeparator, result, i);
dec(i,3);
end;
end; // dotted
function getRes(name:pchar; typ:string='TEXT'):string;
var
h1, h2: Thandle;
p: pAnsiChar;
l: integer;
ansi: ansiString;
begin
result:='';
h1:=FindResource(HInstance, name, pchar(typ));
h2:=LoadResource(HInstance, h1);
if h2=0 then exit;
l:=SizeOfResource(HInstance, h1);
p:=LockResource(h2);
setLength(ansi, l);
move(p^, ansi[1], l);
UnlockResource(h2);
FreeResource(h2);
result:=UTF8toString(ansi);
end; // getRes
function compare_(i1,i2:int64):integer; overload;
begin
if i1 < i2 then result:=-1 else
if i1 > i2 then result:=1 else
result:=0
end; // compare_
function compare_(i1,i2:integer):integer; overload;
begin
if i1 < i2 then result:=-1 else
if i1 > i2 then result:=1 else
result:=0
end; // compare_
function compare_(i1,i2:double):integer; overload;
begin
if i1 < i2 then result:=-1 else
if i1 > i2 then result:=1 else
result:=0
end; // compare_
function rectToStr(r:Trect):string;
begin result:=format('%d,%d,%d,%d',[r.left,r.top,r.right,r.bottom]) end;
function strToRect(s:string):Trect;
begin
result.Left:=strToInt(chop(',',s));
result.Top:=strToInt(chop(',',s));
result.right:=strToInt(chop(',',s));
result.bottom:=strToInt(chop(',',s));
end; // strToRect
function TLV(t:integer; s:string):ansistring;
var
raw: ansistring;
begin
raw:=UTF8encode(s);
if length(raw) > length(s) then
inc(t, TLV_UTF8_FLAG);
result:=str_(t)+str_(length(raw))+raw
end;
function TLV(t:integer; data:ansistring):ansistring;
begin result:=str_(t)+str_(length(data))+data end;
function TLV_NOT_EMPTY(t:integer; data:ansistring):ansistring;
begin if data > '' then result:=TLV(t,data) else result:='' end;
function TLV_NOT_EMPTY(t:integer; s:string):ansistring;
begin if s > '' then result:=TLV(t,s) else result:='' end;
function getCRC(data:ansistring):integer;
var
i:integer;
p:Pinteger;
begin
result:=0;
p:=@data[1];
for i:=1 to length(data) div 4 do
begin
inc(result, p^);
inc(p);
end;
end; // crc
function bmpToHico(bitmap:Tbitmap):hicon;
var
iconX, iconY : integer;
IconInfo: TIconInfo;
IconBitmap, MaskBitmap: TBitmap;
dx,dy,x,y: Integer;
tc: TColor;
begin
if bitmap=NIL then
begin
result:=0;
exit;
end;
iconX := GetSystemMetrics(SM_CXICON);
iconY := GetSystemMetrics(SM_CYICON);
IconBitmap:= TBitmap.Create;
IconBitmap.Width:= iconX;
IconBitmap.Height:= iconY;
IconBitmap.TransparentColor:=Bitmap.TransparentColor;
tc:=Bitmap.TransparentColor and $FFFFFF;
Bitmap.transparent:=FALSE;
dx:=bitmap.width*2;
dy:=bitmap.height*2;
if (dx < iconX) and (dy < iconY) then
begin
IconBitmap.Canvas.brush.color:=tc;
with IconBitmap.Canvas do fillrect(clipRect);
x:=(iconX-dx) div 2;
y:=(iconY-dy) div 2;
IconBitmap.Canvas.StretchDraw(Rect(x,y,x+dx,y+dy), Bitmap);
end
else
IconBitmap.Canvas.StretchDraw(Rect(0, 0, iconX, iconY), Bitmap);
MaskBitmap:= TBitmap.Create;
MaskBitmap.Assign(IconBitmap);
with MaskBitmap.canvas do fillrect(cliprect);
IconInfo.fIcon:= True;
IconInfo.hbmMask:= MaskBitmap.MaskHandle;
IconInfo.hbmColor:= IconBitmap.Handle;
Result:= CreateIconIndirect(IconInfo);
MaskBitmap.Free;
IconBitmap.Free;
end; // bmpToHico
function msgDlg(msg:string; code:integer=0; title:string=''):integer;
var
parent: Thandle;
begin
result:=0;
if msg='' then exit;
if code = 0 then code:=MB_OK+MB_ICONINFORMATION;
if screen.ActiveCustomForm = NIL then parent:=0
else parent:=screen.ActiveCustomForm.handle;
application.restore();
application.BringToFront();
title:=application.Title+nonEmptyConcat(' -- ', title);
result:=messageBox(parent, pchar(msg), pchar(title), code)
end; // msgDlg
function idxOf(s:string; a:array of string; isSorted:boolean=FALSE):integer;
var
r, b, e: integer;
begin
if not isSorted then
begin
result:=ansiIndexText(s,a);
exit;
end;
// a classic one... :-P
b:=0;
e:=length(a)-1;
while b <= e do
begin
result:=(b+e) div 2;
r:=ansiCompareText(s, a[result]);
if r = 0 then exit;
if r < 0 then e:=result-1
else b:=result+1;
end;
result:=-1;
end;
function stringExists(s:string; a:array of string; isSorted:boolean=FALSE):boolean;
begin result:= idxOf(s,a, isSorted) >= 0 end;
function validUsername(s:string; acceptEmpty:boolean=FALSE):boolean;
begin
result:=(s = '') and acceptEmpty
or (s > '') and not anycharIn('/\:?*"<>|;&',s) and (length(s) <= 40)
and not anyMacroMarkerIn(s) // mod by mars
end;
function validFilename(s:string):boolean;
begin
result:=(s>'')
and not dirCrossing(s)
and not anycharIn(ILLEGAL_FILE_CHARS,s)
end;
function validFilepath(fn:string; acceptUnits:boolean=TRUE):boolean;
var
withUnit: boolean;
begin
withUnit:=(length(fn) > 2) and charInSet(fn[1], ['a'..'z','A'..'Z']) and (fn[2] = ':');
result:=(fn > '')
and (posEx(':', fn, if_(withUnit,3,1)) = 0)
and (poss([#0..#31,'?','*','"','<','>','|'], fn) = 0)
and (length(fn) <= 255+if_(withUnit, 2));
end;
function loadTextFile(fn:string):string;
begin result:=UTF8toString(loadfile(fn)) end;
function loadFile(fn:string; from:int64=0; size:int64=-1):ansistring;
var
f:file;
bak: byte;
begin
result:='';
IOresult;
if not validFilepath(fn) then exit;
if not isAbsolutePath(fn) then chDir(exePath);
assignFile(f, fn);
bak:=fileMode;
fileMode:=0;
try
reset(f,1);
if IOresult <> 0 then exit;
if (size < 0) or (size > filesize(f)-from) then
size:=filesize(f)-from;