-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathKLib.Utils.pas
1946 lines (1640 loc) · 53.3 KB
/
KLib.Utils.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
{
KLib Version = 3.0
The Clear BSD License
Copyright (c) 2020 by Karol De Nery Ortiz LLave. All rights reserved.
zitrokarol@gmail.com
Redistribution and use in source and binary forms, with or without
modification, are permitted (subject to the limitations in the disclaimer
below) provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY
THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
}
unit KLib.Utils;
interface
uses
KLib.Types, KLib.Constants, KLib.MyThread,
Vcl.Imaging.pngimage,
System.SysUtils, System.Classes;
procedure deleteFilesInDir(pathDir: string; const filesToKeep: array of string);
procedure deleteFilesInDirWithStartingFileName(dirName: string; startingFileName: string; fileType: string = EMPTY_STRING);
procedure createEmptyFileIfNotExists(filename: string);
procedure createEmptyFile(filename: string);
procedure deleteFileIfExists(fileName: string);
function checkIfFileExistsAndIsEmpty(fileName: string): boolean;
function checkIfFileExistsAndIsNotEmpty(fileName: string): boolean;
function checkIfFileIsEmpty(fileName: string): boolean;
function checkIfFileExistsInSystem32(filename: string): boolean;
function checkIfFileExists(fileName: string): boolean;
procedure replaceTextInFile(oldText: string; newText: string; filename: string; filenameOutput: string = EMPTY_STRING;
replaceFlags: TReplaceFlags = [rfReplaceAll]);
function getTextFromFile(fileName: string): string;
function checkIfThereIsSpaceAvailableOnDrive(drive: char; requiredSpaceInBytes: int64): boolean;
function getFreeSpaceOnDrive(drive: char): int64;
function getIndexOfDrive(drive: char): integer;
function getDriveExe: char;
function getDirSize(path: string): int64;
procedure createDirIfNotExists(dirName: string);
function checkIfDirExists(dirName: string): boolean;
function checkIfIsLinuxSubDir(subDir: string; mainDir: string): boolean;
function getPathInLinuxStyle(path: string): string;
function checkIfIsSubDir(subDir: string; mainDir: string; trailingPathDelimiter: char = SPACE_STRING): boolean;
function getValidFullPath(fileName: string): string;
function checkIfIsAPath(path: string): boolean;
function getCombinedPath(path1: string; path2: string): string;
function getTempfolderPath: string;
function getParentDir(source: string): string;
function getFirstFileNameInDir(dirName: string; fileType: string = EMPTY_STRING; fullPath: boolean = true): string;
function getFileNamesListInDir(dirName: string; fileType: string = EMPTY_STRING; fullPath: boolean = true): TStringList;
procedure appendToFileInNewLine(filename: string; text: string; forceCreationFile: boolean = NOT_FORCE); overload;
procedure appendToFile(filename: string; text: string; forceCreationFile: boolean = NOT_FORCE;
forceAppendInNewLine: boolean = NOT_FORCE); overload;
procedure saveToFile(source: string; fileName: string);
function checkMD5File(fileName: string; MD5: string): boolean;
procedure unzipResource(nameResource: string; destinationDir: string);
function getPNGResource(nameResource: string): TPngImage;
procedure getResourceAsEXEFile(nameResource: string; destinationFileName: string);
procedure getResourceAsZIPFile(nameResource: string; destinationFileName: string);
procedure getResourceAsFile(resource: TResource; destinationFileName: string);
function getResourceAsString(resource: TResource): string;
function getResourceAsStream(resource: TResource): TResourceStream;
procedure unzip(zipFileName: string; destinationDir: string; deleteZipAfterUnzip: boolean = false);
function checkRequiredFTPProperties(FTPCredentials: TFTPCredentials): boolean;
function splitByMonths(startDate: TDateTime; endDate: TDateTime): TArray<TDateTimeRange>; overload;
function splitByMonths(datetimeRange: TDateTimeRange): TArray<TDateTimeRange>; overload;
function divideDateRange(startDate: TDateTime; endDate: TDateTime; divisions: integer = 2): TArray<TDateTimeRange>; overload;
function divideDateRange(datetimeRange: TDateTimeRange; divisions: integer = 2): TArray<TDateTimeRange>; overload;
function getValidItalianTelephoneNumber(number: string): string;
function getValidTelephoneNumber(number: string): string;
function getRandString(size: integer = 5): string;
function getCurrentDayOfWeekAsString: string;
function getDayOfWeekAsString(date: TDateTime): string;
function getCurrentDateTimeAsString: string;
function getDateTimeAsString(date: TDateTime): string;
function getCurrentDateAsString: string;
function getDateAsString(date: TDateTime): string;
function getCurrentTimeStamp: string;
function getCurrentDateTimeWithFormattingAsString(formatting: string = DATE_FORMAT): string;
function getDateTimeWithFormattingAsString(value: TDateTime; formatting: string = DATE_FORMAT): string;
function getCurrentDateTime: TDateTime;
function getEscapedMySQLString(mainString: string): string;
function getHTTPGetEncodedUrl(url: string; paramList: TStringList): string;
function getEscapedHTMLString(mainString: string): string;
function getEscapedXMLString(mainString: string): string;
function getEscapedJSONString(mainString: string): string;
function getDoubleQuotedString(mainString: string): string;
function getSingleQuotedString(mainString: string): string;
function getQuotedString(mainString: string; quoteCharacter: Char): string;
function getDoubleQuoteExtractedString(mainString: string; isRaiseExceptionEnabled: boolean = RAISE_EXCEPTION_DISABLED): string;
function getSingleQuoteExtractedString(mainString: string; isRaiseExceptionEnabled: boolean = RAISE_EXCEPTION_DISABLED): string;
function getExtractedString(mainString: string; quoteString: string; isRaiseExceptionEnabled: boolean = RAISE_EXCEPTION_DISABLED): string;
function getDequotedString(mainString: string): string;
function getMainStringWithSubStringInserted(mainString: string; insertedString: string; index: integer;
forceOverwriteIndexCharacter: boolean = NOT_FORCE_OVERWRITE): string;
function getStringWithoutLineBreaks(mainString: string; substituteString: string = SPACE_STRING): string;
function getStringWithFixedLength(value: string; fixedLength: integer): string;
function getStringFromStream(stream: TStream): string;
function getCSVFieldFromStringAsDate(mainString: string; index: integer; delimiter: Char = SEMICOLON_DELIMITER): TDate; overload;
function getCSVFieldFromStringAsDate(mainString: string; index: integer; formatSettings: TFormatSettings; delimiter: Char = SEMICOLON_DELIMITER): TDate; overload;
function getCSVFieldFromStringAsDouble(mainString: string; index: integer; delimiter: Char = SEMICOLON_DELIMITER): Double; overload;
function getCSVFieldFromStringAsDouble(mainString: string; index: integer; formatSettings: TFormatSettings; delimiter: Char = SEMICOLON_DELIMITER): Double; overload;
function getCSVFieldFromStringAsInteger(mainString: string; index: integer; delimiter: Char = SEMICOLON_DELIMITER): integer;
function getCSVFieldFromString(mainString: string; index: integer; delimiter: Char = SEMICOLON_DELIMITER): string;
function getNumberOfLinesInStrFixedWordWrap(source: string): integer;
function stringToStrFixedWordWrap(source: string; fixedLen: Integer): string;
function stringToStringListWithFixedLen(source: string; fixedLen: Integer): TStringList;
function stringToStringListWithDelimiter(value: string; delimiter: Char): TStringList;
function stringToTStringList(source: string): TStringList;
function stringToVariantType(stringValue: string; destinationTypeAsString: string): Variant;
function arrayOfStringToTStringList(arrayOfStrings: array of string): TStringList;
function arrayOfVariantToTStringList(arrayOfVariant: Variant): TStringList;
procedure splitStrings(source: string; delimiter: string; var destFirstString: string; var destSecondString: string); overload;
procedure splitStrings(source: string; delimiterPosition: integer; delimiterLength: integer; var destFirstString: string; var destSecondString: string); overload;
function getMergedStrings(firstString: string; secondString: string; delimiter: string = EMPTY_STRING): string;
function checkIfEmailIsValid(email: string): boolean;
function checkIfRegexIsValid(text: string; regex: string): boolean;
function checkIfMainStringContainsSubStringNoCaseSensitive(mainString: string; subString: string): boolean;
function checkIfMainStringContainsSubString(mainString: string; subString: string; caseSensitiveSearch: boolean = CASE_SENSITIVE): boolean;
function myStringReplace(mainString: string; OldPattern: array of string; NewPattern: array of string; Flags: TReplaceFlags): string; overload;
function myStringReplace(const SourceString, OldPattern, NewPattern: string; Flags: TReplaceFlags): string; overload;
function myAnsiPos(subString: string; mainString: string; caseSensitiveSearch: boolean = CASE_SENSITIVE): integer;
function getDoubleAsString(value: Double; decimalSeparator: char = DECIMAL_SEPARATOR_IT): string;
function getFloatToStrDecimalSeparator: char;
function get_status_asString(status: TStatus): string;
procedure restartMyThread(var myThread: TMyThread);
//TODO refactor
function getBitValueOfWord(const sourceValue: Cardinal; const bitIndex: Byte): Boolean;
function getWordWithBitEnabled(const sourceValue: Cardinal; const bitIndex: Byte): Cardinal;
function getWordWithBitDisabled(const sourceValue: Cardinal; const bitIndex: Byte): Cardinal;
function getWordWithBitSetted(const sourceValue: Cardinal; const bitIndex: Byte; const bitValue: Boolean): Cardinal;
function getArrayOfAnonymousMethodsFromArrayOfMethods(_methods: KLib.Types.TArrayOfMethods): KLib.Types.TArrayOfAnonymousMethods;
function getAnonymousMethodsFromMethod(_method: KLib.Types.TMethod): KLib.Types.TAnonymousMethod;
procedure tryToExecuteProcedure(myProcedure: TAnonymousMethod; isRaiseExceptionEnabled: boolean = false); overload;
procedure tryToExecuteProcedure(myProcedure: TCallBack; isRaiseExceptionEnabled: boolean = false); overload;
procedure tryToExecuteProcedure(myProcedure: TProcedure; isRaiseExceptionEnabled: boolean = false); overload;
procedure executeProcedure(myProcedure: TAnonymousMethod); overload;
procedure executeProcedure(myProcedure: TCallBack); overload;
function checkIfVariantTypeIsEmpty(value: Variant; typeAsString: string): boolean;
function checkIfIsEmptyOrNull(value: Variant): boolean;
function myDefault(typeAsString: string): Variant;
function myIsDebuggerPresent: boolean;
implementation
uses
KLib.Validate, KLib.Indy, KLib.FileSearchReplacer, KLib.Math,
Vcl.ExtCtrls,
System.Zip, System.IOUtils, System.StrUtils, System.Character, System.RegularExpressions,
System.Variants, System.NetEncoding, System.DateUtils;
procedure deleteFilesInDir(pathDir: string; const filesToKeep: array of string);
var
_fileNamesList: TStringList;
_fileName: string;
_nameOfFile: string;
_keepFile: boolean;
begin
validateThatDirExists(pathDir);
_fileNamesList := getFileNamesListInDir(pathDir);
try
for _fileName in _fileNamesList do
begin
_nameOfFile := ExtractFileName(_fileName);
_keepFile := MatchText(_nameOfFile, filesToKeep);
if not _keepFile then
begin
deleteFileIfExists(_fileName);
end;
end;
finally
FreeAndNil(_fileNamesList);
end;
end;
procedure deleteFilesInDirWithStartingFileName(dirName: string; startingFileName: string; fileType: string = EMPTY_STRING);
const
IGNORE_CASE = true;
var
_files: TStringList;
_file: string;
_fileName: string;
begin
_files := getFileNamesListInDir(dirName, fileType);
for _file in _files do
begin
_fileName := ExtractFileName(_file);
if _fileName.StartsWith(startingFileName, IGNORE_CASE) then
begin
deleteFileIfExists(_file);
end;
end;
FreeAndNil(_files);
end;
procedure createEmptyFileIfNotExists(filename: string);
begin
if not checkIfFileExists(filename) then
begin
createEmptyFile(filename);
end;
end;
{$hints OFF}
procedure createEmptyFile(filename: string);
var
_handle: THandle;
begin
_handle := FileCreate(fileName);
if _handle = INVALID_HANDLE_VALUE then
begin
raise Exception.Create('Error creating file: ' + fileName);
end
else
begin
FileClose(_handle);
end;
end;
{$hints ON}
procedure deleteFileIfExists(fileName: string);
const
ERR_MSG = 'Error deleting file.';
begin
if checkIfFileExists(fileName) then
begin
if not DeleteFile(pchar(fileName)) then
begin
raise Exception.Create(ERR_MSG);
end;
end;
end;
function checkIfFileExistsAndIsEmpty(fileName: string): boolean;
var
fileExistsAndIsEmpty: boolean;
begin
fileExistsAndIsEmpty := checkIfFileExists(fileName) and checkIfFileIsEmpty(fileName);
Result := fileExistsAndIsEmpty;
end;
function checkIfFileExistsAndIsNotEmpty(fileName: string): boolean;
var
fileExistsAndIsNotEmpty: boolean;
begin
fileExistsAndIsNotEmpty := checkIfFileExists(fileName) and (not checkIfFileIsEmpty(fileName));
Result := fileExistsAndIsNotEmpty;
end;
function checkIfFileIsEmpty(fileName: string): boolean;
var
fileIsEmpty: boolean;
_file: file of Byte;
_size: integer;
begin
AssignFile(_file, fileName);
Reset(_file);
_size := FileSize(_file);
fileIsEmpty := _size = 0;
CloseFile(_file);
Result := fileIsEmpty;
end;
function checkIfFileExistsInSystem32(filename: string): boolean;
var
fileExistsInSystem32: boolean;
_fileName: string;
_filenameIsAPath: boolean;
begin
_fileName := filename;
_filenameIsAPath := checkIfIsAPath(_fileName);
if _filenameIsAPath then
begin
validateThatIsWindowsSubDir(_fileName, WINDOWS_SYSTEM32_PATH);
end
else
begin
_fileName := getCombinedPath(WINDOWS_SYSTEM32_PATH, _fileName);
end;
fileExistsInSystem32 := checkIfFileExists(_fileName);
Result := fileExistsInSystem32;
end;
function checkIfFileExists(fileName: string): boolean;
begin
Result := FileExists(fileName);
end;
procedure replaceTextInFile(oldText: string; newText: string; filename: string; filenameOutput: string = EMPTY_STRING;
replaceFlags: TReplaceFlags = [rfReplaceAll]);
var
_fileSearchReplacer: TFileSearchReplacer;
begin
_fileSearchReplacer := TFileSearchReplacer.Create(filename, filenameOutput);
try
_fileSearchReplacer.replace(oldText, newText, replaceFlags);
finally
_fileSearchReplacer.Free;
end;
end;
function getTextFromFile(fileName: string): string;
var
text: string;
_stringList: TStringList;
begin
_stringList := TStringList.Create;
try
_stringList.LoadFromFile(fileName);
text := _stringList.Text;
finally
_stringList.Free;
end;
Result := text;
end;
function checkIfThereIsSpaceAvailableOnDrive(drive: char; requiredSpaceInBytes: int64): boolean;
var
isSpaceAvailableOnDrive: boolean;
_freeSpaceDrive: int64;
begin
_freeSpaceDrive := getFreeSpaceOnDrive(drive);
isSpaceAvailableOnDrive := _freeSpaceDrive > requiredSpaceInBytes;
Result := isSpaceAvailableOnDrive;
end;
function getFreeSpaceOnDrive(drive: char): int64;
const
ERR_MSG_INVALID_DRIVE = 'The drive is invalid.';
ERR_MSG_DRIVE_READ_ONLY = 'The drive is read-only';
var
freeSpaceOnDrive: int64;
_indexOfDrive: integer;
begin
_indexOfDrive := getIndexOfDrive(drive);
freeSpaceOnDrive := DiskFree(_indexOfDrive);
case freeSpaceOnDrive of
- 1:
raise Exception.Create(ERR_MSG_INVALID_DRIVE);
0:
raise Exception.Create(ERR_MSG_DRIVE_READ_ONLY);
end;
Result := freeSpaceOnDrive;
end;
function getIndexOfDrive(drive: char): integer;
const
ASCII_FIRST_ALPHABET_CHARACTER = 65;
ASCII_LAST_ALPHABET_CHARACTER = 90;
ERR_MSG = 'Invalid drive character.';
var
indexOfDrive: integer;
_drive: string;
_asciiIndex: integer;
begin
_drive := uppercase(drive);
_asciiIndex := integer(_drive[1]);
if not((_asciiIndex >= ASCII_FIRST_ALPHABET_CHARACTER) and (_asciiIndex <= ASCII_LAST_ALPHABET_CHARACTER)) then
begin
raise Exception.Create(ERR_MSG);
end;
indexOfDrive := (_asciiIndex - ASCII_FIRST_ALPHABET_CHARACTER) + 1;
Result := indexOfDrive;
end;
function getDriveExe: char;
var
driveExe: char;
_dirExe: string;
begin
_dirExe := getDriveExe;
driveExe := _dirExe[1];
Result := driveExe;
end;
function getDirSize(path: string): int64;
var
dirSize: int64;
_searchRec: TSearchRec;
_subDirSize: int64;
begin
dirSize := 0;
path := getValidFullPath(path);
path := IncludeTrailingPathDelimiter(path);
if FindFirst(path + '*', faAnyFile, _searchRec) = 0 then
begin
repeat
if (_searchRec.attr and faDirectory) > 0 then
begin
if (_searchRec.name <> '.') and (_searchRec.name <> '..') then
begin
_subDirSize := getDirSize(path + _searchRec.name);
inc(dirSize, _subDirSize);
end;
end
else
begin
inc(dirSize, _searchRec.size);
end;
until FindNext(_searchRec) <> 0;
System.SysUtils.FindClose(_searchRec);
end;
Result := dirSize;
end;
procedure createDirIfNotExists(dirName: string);
const
ERR_MSG = 'Error creating dir.';
begin
if not checkIfDirExists(dirName) then
begin
if not CreateDir(dirName) then
begin
raise Exception.Create(ERR_MSG);
end;
end;
end;
function checkIfDirExists(dirName: string): boolean;
begin
Result := DirectoryExists(dirName);
end;
function checkIfIsLinuxSubDir(subDir: string; mainDir: string): boolean;
var
isSubDir: boolean;
_subDir: string;
_mainDir: string;
begin
_subDir := getPathInLinuxStyle(subDir);
_mainDir := getPathInLinuxStyle(mainDir);
isSubDir := checkIfIsSubDir(_subDir, _mainDir, LINUX_PATH_DELIMITER);
Result := isSubDir
end;
function getPathInLinuxStyle(path: string): string;
var
pathInLinuxStyle: string;
begin
pathInLinuxStyle := myStringReplace(path, '\', '/', [rfReplaceAll, rfIgnoreCase]);
Result := pathInLinuxStyle;
end;
function checkIfIsSubDir(subDir: string; mainDir: string; trailingPathDelimiter: char = SPACE_STRING): boolean;
var
isSubDir: boolean;
_subDir: string;
_mainDir: string;
_trailingPathDelimiter: char;
begin
_subDir := LowerCase(subDir);
_mainDir := LowerCase(mainDir);
_trailingPathDelimiter := trailingPathDelimiter;
if _trailingPathDelimiter = SPACE_STRING then
begin
_trailingPathDelimiter := PathDelim;
end;
if not(AnsiRightStr(_mainDir, 1) = _trailingPathDelimiter) then
begin
_mainDir := _mainDir + _trailingPathDelimiter;
end;
isSubDir := AnsiStartsStr(_mainDir, _subDir);
Result := isSubDir;
end;
function getValidFullPath(fileName: string): string;
var
path: string;
begin
path := fileName;
path := ExpandFileName(path);
path := ExcludeTrailingPathDelimiter(path);
Result := path;
end;
function checkIfIsAPath(path: string): boolean;
begin
Result := ExtractFilePath(path) <> EMPTY_STRING;
end;
function getCombinedPath(path1: string; path2: string): string;
begin
Result := TPath.Combine(path1, path2);
end;
function getTempfolderPath: string;
var
path: string;
begin
path := TPath.GetTempPath;
path := ExcludeTrailingPathDelimiter(path);
Result := path;
end;
function getParentDir(source: string): string;
var
parentDir: string;
begin
parentDir := getValidFullPath(source);
parentDir := ExtractFilePath(parentDir);
Result := parentDir;
end;
function getFirstFileNameInDir(dirName: string; fileType: string = EMPTY_STRING; fullPath: boolean = true): string;
const
ERR_MSG = 'No files found.';
var
fileName: string;
_fileNamesList: TStringList;
begin
_fileNamesList := getFileNamesListInDir(dirName, fileType, fullPath);
if _fileNamesList.Count > 0 then
begin
fileName := _fileNamesList[0];
end
else
begin
fileName := EMPTY_STRING;
end;
FreeAndNil(_fileNamesList);
if fileName = EMPTY_STRING then
begin
raise Exception.Create(ERR_MSG);
end;
Result := fileName;
end;
function getFileNamesListInDir(dirName: string; fileType: string = EMPTY_STRING; fullPath: boolean = true): TStringList;
var
fileNamesList: TStringList;
_searchRec: TSearchRec;
_mask: string;
_fileExists: boolean;
_fileName: string;
_returnCode: integer;
_errorMsg: string;
begin
fileNamesList := TStringList.Create;
_mask := getCombinedPath(dirName, '*');
if fileType <> EMPTY_STRING then
begin
_mask := _mask + '.' + fileType;
end;
_returnCode := FindFirst(_mask, faAnyFile - faDirectory, _searchRec);
if (_returnCode <> 0) and (_returnCode <> 2) then
begin
_errorMsg := dirName + ' : ' + SysErrorMessage(_returnCode);
raise Exception.Create(_errorMsg);
end;
_fileExists := _returnCode = 0;
while _fileExists do
begin
_fileName := _searchRec.Name;
if fullPath then
begin
_fileName := getCombinedPath(dirName, _fileName);
end;
fileNamesList.Add(_fileName);
_fileExists := FindNext(_searchRec) = 0;
end;
Result := fileNamesList;
end;
procedure appendToFileInNewLine(filename: string; text: string; forceCreationFile: boolean = NOT_FORCE);
begin
appendToFile(fileName, text, forceCreationFile, FORCE);
end;
procedure appendToFile(filename: string; text: string; forceCreationFile: boolean = NOT_FORCE;
forceAppendInNewLine: boolean = NOT_FORCE);
var
_text: string;
begin
if forceCreationFile then
begin
createEmptyFileIfNotExists(filename);
end;
_text := text;
if (checkIfFileExistsAndIsNotEmpty(filename)) then
begin
if (forceAppendInNewLine) then
begin
_text := sLineBreak + _text;
end;
end;
TFile.AppendAllText(filename, _text);
end;
procedure saveToFile(source: string; fileName: string);
var
_stringList: TStringList;
begin
try
_stringList := stringToTStringList(source);
_stringList.SaveToFile(fileName);
finally
FreeAndNil(_stringList);
end;
end;
function checkMD5File(fileName: string; MD5: string): boolean;
var
MD5CheckedStatus: boolean;
_MD5ChecksumFile: string;
begin
_MD5ChecksumFile := getMD5ChecksumFile(fileName);
MD5CheckedStatus := (UpperCase(_MD5ChecksumFile) = UpperCase(MD5));
Result := MD5CheckedStatus;
end;
procedure unzipResource(nameResource: string; destinationDir: string);
const
DELETE_ZIP_AFTER_UNZIP = TRUE;
var
_tempZipFileName: string;
begin
_tempZipFileName := getRandString + '.' + ZIP_TYPE;
_tempZipFileName := getCombinedPath(destinationDir, _tempZipFileName);
getResourceAsZIPFile(nameResource, _tempZipFileName);
unzip(_tempZipFileName, destinationDir, DELETE_ZIP_AFTER_UNZIP);
end;
function getPNGResource(nameResource: string): TPngImage;
var
resourceAsPNG: TPngImage;
_resource: TResource;
_resourceStream: TResourceStream;
begin
with _resource do
begin
name := nameResource;
_type := PNG_TYPE;
end;
_resourceStream := getResourceAsStream(_resource);
resourceAsPNG := TPngImage.Create;
resourceAsPNG.LoadFromStream(_resourceStream);
_resourceStream.Free;
Result := resourceAsPNG;
end;
procedure _getResourceAsFile_(nameResource: string; typeResource: string; destinationFileName: string); forward;
procedure getResourceAsEXEFile(nameResource: string; destinationFileName: string);
begin
_getResourceAsFile_(nameResource, EXE_TYPE, destinationFileName);
end;
procedure getResourceAsZIPFile(nameResource: string; destinationFileName: string);
begin
_getResourceAsFile_(nameResource, ZIP_TYPE, destinationFileName);
end;
procedure _getResourceAsFile_(nameResource: string; typeResource: string; destinationFileName: string);
var
_resource: TResource;
_destinationFileName: string;
begin
with _resource do
begin
name := nameResource;
_type := typeResource;
end;
_destinationFileName := destinationFileName;
if not LowerCase(_destinationFileName).EndsWith('.' + LowerCase(typeResource)) then
begin
_destinationFileName := _destinationFileName + '.' + LowerCase(typeResource);
end;
getResourceAsFile(_resource, _destinationFileName);
end;
procedure getResourceAsFile(resource: TResource; destinationFileName: string);
var
_resourceStream: TResourceStream;
_destinationDirPath: string;
begin
_destinationDirPath := getParentDir(destinationFileName);
validateThatDirExists(_destinationDirPath);
_resourceStream := getResourceAsStream(resource);
_resourceStream.SaveToFile(destinationFileName);
_resourceStream.Free;
end;
function getResourceAsString(resource: TResource): string;
var
resourceAsString: string;
_resourceStream: TResourceStream;
_stringList: TStringList;
begin
resourceAsString := '';
_resourceStream := getResourceAsStream(resource);
_stringList := TStringList.Create;
_stringList.LoadFromStream(_resourceStream);
resourceAsString := _stringList.Text;
_resourceStream.Free;
Result := resourceAsString;
end;
function getResourceAsStream(resource: TResource): TResourceStream;
var
resourceStream: TResourceStream;
_errMsg: string;
begin
with resource do
begin
if (FindResource(hInstance, PChar(name), PChar(_type)) <> 0) then
begin
resourceStream := TResourceStream.Create(HInstance, PChar(name), PChar(_type));
resourceStream.Position := 0;
end
else
begin
_errMsg := 'Not found a resource with name : ' + name + ' and type : ' + _type;
raise Exception.Create(_errMsg);
end;
end;
Result := resourceStream;
end;
procedure unzip(zipFileName: string; destinationDir: string; deleteZipAfterUnzip: boolean = false);
const
ERR_MSG = 'Invalid zip file.';
begin
if TZipFile.isvalid(zipFileName) then
begin
TZipFile.extractZipfile(zipFileName, destinationDir);
if (deleteZipAfterUnzip) then
begin
deleteFileIfExists(zipFileName);
end;
end
else
begin
raise Exception.Create(ERR_MSG);
end;
end;
function checkRequiredFTPProperties(FTPCredentials: TFTPCredentials): boolean;
var
_result: boolean;
begin
with FTPCredentials do
begin
_result := (server <> EMPTY_STRING) and (credentials.username <> EMPTY_STRING) and (credentials.password <> EMPTY_STRING)
and (port >= 0);
end;
Result := _result;
end;
function splitByMonths(startDate: TDateTime; endDate: TDateTime): TArray<TDateTimeRange>;
var
_datetimeRange: TDateTimeRange;
begin
_datetimeRange.clear;
_datetimeRange._start := startDate;
_datetimeRange._end := endDate;
Result := splitByMonths(_datetimeRange);
end;
function splitByMonths(datetimeRange: TDateTimeRange): TArray<TDateTimeRange>;
var
dateRanges: TArray<TDateTimeRange>;
range: TDateTimeRange;
currentStart: TDateTime;
currentEnd: TDateTime;
year, month, day: Word;
begin
if datetimeRange._start > datetimeRange._end then
raise Exception.Create('The start date must be earlier than the end date.');
currentStart := datetimeRange._start;
while currentStart <= datetimeRange._end do
begin
range.clear;
// Decode the current start date
DecodeDate(currentStart, year, month, day);
// Calculate the end of the current month
currentEnd := EncodeDate(year, month, DaysInAMonth(year, month));
// Ensure the current end does not exceed the provided range
if currentEnd > datetimeRange._end then
currentEnd := datetimeRange._end;
// Assign the range
range._start := currentStart;
range._end := currentEnd;
// Add the range to the array
SetLength(dateRanges, Length(dateRanges) + 1);
dateRanges[High(dateRanges)] := range;
// Move to the next month
currentStart := currentEnd + 1;
end;
Result := dateRanges;
end;
function divideDateRange(startDate: TDateTime; endDate: TDateTime; divisions: Integer = 2): TArray<TDateTimeRange>;
var
_datetimeRange: TDateTimeRange;
begin
_datetimeRange.clear;
_datetimeRange._start := startDate;
_datetimeRange._end := endDate;
Result := divideDateRange(_datetimeRange, divisions);
end;
function divideDateRange(datetimeRange: TDateTimeRange; divisions: Integer = 2): TArray<TDateTimeRange>;
var
dateRanges: TArray<TDateTimeRange>;
i: Integer;
interval: TDateTime;
currentStart: TDateTime;
range: TDateTimeRange;
begin
if (datetimeRange._start > datetimeRange._end) then
begin
raise Exception.Create('The start date must be earlier than the end date.');
end;
if (divisions <= 0) then
begin
raise Exception.Create('The number of divisions must be greater than 0.');
end;
if (divisions > Trunc(datetimeRange._end - datetimeRange._start) + 1) then
begin
raise Exception.Create('The number of divisions exceeds the number of days in the range.');
end;
// Calculate the interval for each division
interval := (datetimeRange._end - datetimeRange._start) / divisions;
// Initialize the result array
SetLength(dateRanges, divisions);
// Create each range
currentStart := datetimeRange._start;
for i := 0 to divisions - 1 do
begin
range.clear;
range._start := currentStart;
if (i = (divisions - 1)) then
begin
range._end := datetimeRange._end; // Ensure the last range ends exactly at endDate
end
else
begin
range._end := Trunc(currentStart + interval);
end;
dateRanges[i] := range;
currentStart := range._end + 1; // Start the next range the day after the current end
end;
Result := dateRanges;
end;
function getValidItalianTelephoneNumber(number: string): string;
var
telephoneNumber: string;
_number: string;
i: integer;
begin
telephoneNumber := '';
_number := trim(number);
if _number = '' then
begin
telephoneNumber := '';
end
else
begin
if _number.StartsWith('0039') then
begin
_number := KLib.Utils.myStringReplace(_number, '0039', '+39', []);
end;
if not _number.StartsWith('+') then
begin
_number := '+39' + _number;
end;
if not _number.StartsWith('+39') then
begin
_number := myStringReplace(_number, '+', '+39', []);
end;