-
Notifications
You must be signed in to change notification settings - Fork 11
/
fpcuputil.pas
executable file
·6155 lines (5640 loc) · 178 KB
/
fpcuputil.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
{ Utility unit for various FPCup versions
Copyright (C) 2012-2014 Reinier Olislagers, Ludo Brands
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version with the following modification:
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent modules,and
to copy and distribute the resulting executable under terms of your choice,
provided that you also meet, for each linked independent module, the terms
and conditions of the license of that module. An independent module is a
module which is not derived from or based on this library. If you modify
this library, you may extend this exception to your version of the library,
but you are not obligated to do so. If you do not wish to do so, delete this
exception statement from your version.
This program 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 Library General Public License
for more details.
You should have received a copy of the GNU Library General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
unit fpcuputil;
{ Utility functions that might be needed by fpcup core and plugin units }
{$mode objfpc}{$H+}
{$i fpcupdefines.inc}
{$if not defined(ENABLEWGET) and not defined(ENABLENATIVE)}
{$error No downloader defined !!! }
{$endif}
interface
uses
Classes, SysUtils, strutils,
typinfo,
zipper,
fphttpclient, // for github api file list and others
{$ifdef darwin}
ns_url_request,
{$endif}
{$ifndef USEONLYCURL}
{$IF NOT DEFINED(MORPHOS) AND NOT DEFINED(AROS)}
{$IF DEFINED(FPC_FULLVERSION) AND (FPC_FULLVERSION >= 30200)}
//fpopenssl,
opensslsockets,
//gnutls,
//gnutlssockets,
{$ENDIF}
openssl,
{$ENDIF}
{$endif USEONLYCURL}
//fpftpclient,
eventlog;
Const
DELUXEKEY='fpcupdeluxeishereforyou';
MAXCONNECTIONRETRIES=2;
{$ifdef Windows}
GetExeExt='.exe';
GetLibExt='.dll';
{$else}
GetExeExt='';
//GetLibExt='.so';
{$endif}
type
{TNormalUnzipper}
TNormalUnzipper = class(TObject)
private
// To get a filetree on Windows: CMD /c "Tree /F /A > Resultant.txt"
FUnZipper: TUnZipper;
FFileCnt: cardinal;
FFileList:TStrings;
FTotalFileCnt: cardinal;
FCurrentFile: string;
FFlat:boolean;
procedure DoOnFile(Sender : TObject; Const AFileName : string);
procedure DoOnProgressEx(Sender : TObject; Const ATotPos, ATotSize: Int64);
public
function DoUnZip(const ASrcFile, ADstDir: String; Files: array of string):boolean;
function DoBUnZip2(const SourceFile, TargetFile: string):boolean;
property Flat:boolean read FFlat write FFlat default False;
end;
{ TLogger }
TLogger = class(TObject)
private
FLog: TEventLog;
function GetLogFile: string;
procedure SetLogFile(AValue: string);
public
constructor Create;
destructor Destroy; override;
procedure WriteLog(Message: string);overload;
procedure WriteLog(EventType: TEventType;Message: string);overload;
property LogFile: string read GetLogFile write SetLogFile;
end;
TBasicDownLoader = Class(TObject)
private
FHTTPProxyPort: integer;
FMaxRetries:byte;
FVerbose:boolean;
FUserAgent: string;
FContentType: string;
FAccept: string;
FUsername: string;
FPassword: string;
FHTTPProxyHost: string;
FHTTPProxyUser: string;
FHTTPProxyPassword: string;
FFilenameOnly:string;
procedure parseFTPHTMLListing(F:TStream;filelist:TStringList);
procedure DoOnWriteStream(Sender: TObject; APos: Int64);
procedure SetUserAgent(AValue:string);virtual;abstract;
procedure SetContentType(AValue:string);virtual;abstract;
procedure SetAccept(AValue:string);virtual;abstract;
protected
procedure SetVerbose(aValue:boolean);virtual;
property MaxRetries : Byte Read FMaxRetries Write FMaxRetries;
property UserAgent: string write SetUserAgent;
property ContentType: string write SetContentType;
property Accept: string write SetAccept;
property Username: string read FUsername;
property Password: string read FPassword;
property HTTPProxyHost: string read FHTTPProxyHost;
property HTTPProxyPort: integer read FHTTPProxyPort;
property HTTPProxyUser: string read FHTTPProxyUser;
property HTTPProxyPassword: string read FHTTPProxyPassword;
property FileNameOnly: string read FFilenameOnly;
property Verbose: boolean write SetVerbose;
public
constructor Create;virtual;
destructor Destroy;override;
procedure setCredentials(user,pass:string);virtual;
procedure setProxy(host:string;port:integer;user,pass:string);virtual;
function getFile(const URL,aFilename:string):boolean;virtual;abstract;
function getStream(const URL:string; aDataStream:TStream):boolean;virtual;abstract;
function getFTPFileList(const URL:string; filelist:TStringList):boolean;virtual;abstract;
function checkURL(const URL:string):boolean;virtual;abstract;
end;
{$ifdef ENABLENATIVE}
TUseNativeDownLoader = Class(TBasicDownLoader)
strict private
{$ifdef Darwin}
aFPHTTPClient:TNSHTTPSendAndReceive;
{$else}
aFPHTTPClient:TFPHTTPClient;
{$endif}
procedure DoProgress(Sender: TObject; Const ContentLength, CurrentPos : Int64);
procedure DoHeaders(Sender : TObject);
procedure DoPassword(Sender: TObject; var {%H-}RepeatRequest: Boolean);
procedure ShowRedirect({%H-}ASender : TObject; Const ASrc : String; Var ADest : String);
function Download(const URL: String; aDataStream:TStream):boolean;
function FTPDownload(Const URL: String; aDataStream:TStream):boolean;
function HTTPDownload(Const URL : String; aDataStream:TStream):boolean;
protected
procedure SetUserAgent(AValue:string);override;
procedure SetContentType(AValue:string);override;
procedure SetAccept(AValue:string);override;
procedure SetVerbose(aValue:boolean);override;
public
constructor Create;override;
destructor Destroy; override;
procedure setProxy(host:string;port:integer;user,pass:string);override;
function getFile(const URL,aFilename:string):boolean;override;
function getStream(const URL:string; aDataStream:TStream):boolean;override;
function getFTPFileList(const URL:string; filelist:TStringList):boolean;override;
function checkURL(const URL:string):boolean;override;
end;
{$endif}
{$ifdef ENABLEWGET}
TUseWGetDownloader = Class(TBasicDownLoader)
strict private
FCURLOk:boolean;
FWGETOk:boolean;
//WGETBinary:string;
procedure AddHeader(const aHeader,aValue:String);
{$ifndef USEONLYCURL}
function WGetDownload(Const URL : String; aDataStream : TStream):boolean;
function WGetFTPFileList(const URL:string; filelist:TStringList):boolean;
{$endif USEONLYCURL}
{$ifdef ENABLECURL}
function LibCurlDownload(Const URL : String; aDataStream : TStream):boolean;
function LibCurlFTPFileList(const URL:string; filelist:TStringList):boolean;
{$endif}
function Download(const URL: String; aDataStream: TStream):boolean;
function FTPDownload(Const URL : String; aDataStream : TStream):boolean;
function HTTPDownload(Const URL : String; aDataStream : TStream):boolean;
protected
procedure SetContentType(AValue:string);override;
procedure SetUserAgent(AValue:string);override;
procedure SetAccept(AValue:string);override;
public
class var
WGETBinary:string;
constructor Create;override;
constructor Create(aWGETBinary:string);
function getFile(const URL,aFilename:string):boolean;override;
function getStream(const URL:string; aDataStream:TStream):boolean;override;
function getFTPFileList(const URL:string; filelist:TStringList):boolean;override;
function checkURL(const URL:string):boolean;override;
end;
{$endif}
(*
*)
{$ifdef USEONLYCURL}
TNativeDownloader = TUseWGetDownloader;
TWGetDownloader = TUseWGetDownloader;
{$else}
{$ifdef ENABLENATIVE}
TNativeDownloader = TUseNativeDownLoader;
{$else}
TNativeDownloader = TUseWGetDownloader;
{$endif}
{$ifdef ENABLEWGET}
TWGetDownloader = TUseWGetDownloader;
{$else}
TWGetDownloader = TUseNativeDownLoader;
{$endif}
{$endif USEONLYCURL}
function MulDiv( a, b, c : Integer ) : Integer;
// Create shortcut on desktop to Target file
procedure CreateDesktopShortCut(Target, TargetArguments, ShortcutName: string; AddContext:boolean=false) ;
// Create shell script in user directory that links to Target
procedure CreateHomeStartLink(Target, TargetArguments, ShortcutName: string);
{$IFDEF MSWINDOWS}
// Delete shortcut on desktop
procedure DeleteDesktopShortcut(ShortcutName: string);
{$ENDIF MSWINDOWS}
function FindFileInDirList(Filename, DirectoryList: String): String;
function FindFileInDir(Filename, Path: String): String;
function FindFileInDirWildCard(Filename, Path: String): String;
// Copy a directory recursive
function DirCopy(SourcePath, DestPath: String): Boolean;
function CheckDirectory(DirectoryName: string):boolean;
// Delete directory and children, even read-only. Equivalent to rm -rf <directory>:
function DeleteDirectoryEx(DirectoryName: string): boolean;
// Recursively delete files with specified name(s), only if path contains specfied directory name somewhere (or no directory name specified):
function DeleteFilesSubDirs(const DirectoryName: string; const Names:TStringList; const OnlyIfPathHas: string): boolean;
// Recursively delete files with specified extension(s),
// only if path contains specfied directory name somewhere (or no directory name specified):
function DeleteFilesExtensionsSubdirs(const DirectoryName: string; const Extensions:TStringList; const OnlyIfPathHas: string): boolean;
// only if filename contains specfied part somewhere
function DeleteFilesNameSubdirs(const DirectoryName: string; const OnlyIfNameHas: string): boolean;
function FileNameFromURL(URL:string):string;
function StripUrl(URL:string): string;
function CompilerVersion(CompilerPath: string): string;
function CompilerRevision(CompilerPath: string): string;
function CompilerABI(CompilerPath: string): string;
function CompilerFPU(CompilerPath: string): string;
procedure VersionFromString(const VersionSnippet:string;out Major,Minor,Build:integer; var Patch: Integer);
function CalculateFullVersion(const Major,Minor,Release:integer):dword;overload;
function CalculateFullVersion(const Major,Minor,Release,Patch:integer):qword;overload;
function CalculateNumericalVersion(VersionSnippet: string): dword;
function VersionFromUrl(URL:string): string;
function ReleaseCandidateFromUrl(aURL:string): integer;
// Download from HTTP (includes Sourceforge redirection support) or FTP
// HTTP download can work with http proxy
function Download(UseWget:boolean; URL, TargetFile: string; HTTPProxyHost: string=''; HTTPProxyPort: integer=0; HTTPProxyUser: string=''; HTTPProxyPassword: string=''): boolean;overload;
function Download(UseWget:boolean; URL: string; aDataStream:TStream; HTTPProxyHost: string=''; HTTPProxyPort: integer=0; HTTPProxyUser: string=''; HTTPProxyPassword: string=''): boolean;overload;
function GetURLDataFromCache(aURL:string; HTTPProxyHost: string=''; HTTPProxyPort: integer=0; HTTPProxyUser: string=''; HTTPProxyPassword: string=''):string;
function GetGitHubFileList(aURL:string;fileurllist:TStringList; bWGet:boolean=false; HTTPProxyHost: string=''; HTTPProxyPort: integer=0; HTTPProxyUser: string=''; HTTPProxyPassword: string=''):boolean;
{$IFDEF MSWINDOWS}
function CheckFileSignature(aFilePath: string): boolean;
// Get Windows major and minor version number (e.g. 5.0=Windows 2000)
function GetWin32Version(out Major,Minor,Build : Integer): Boolean;
function CheckWin32Version(aMajor,aMinor: Integer): Boolean;
function IsWindows64: boolean;
// Get path for Windows per user storage of application data. Useful for storing settings
function GetWindowsDownloadFolder: string;
function GetWindowsAppDataFolder: string;
{$ENDIF MSWINDOWS}
//check if there is at least one directory between Dir and root
function ParentDirectoryIsNotRoot(Dir:string):boolean;
// Moves file if it exists, overwriting destination file
function MoveFile(const SrcFilename, DestFilename: string): boolean;
// Correct line-endings
function FileCorrectLineEndings(const SrcFilename, DestFilename: string): boolean;
// Correct directory separators
function FixPath(const s:string):string;
function FileIsReadOnly(const s:string):boolean;
function MaybeQuoted(const s:string):string;
function MaybeQuotedSpacesOnly(const s:string):string;
function OccurrencesOfChar(const ContentString: string; const CharToCount: char): integer;
// Like ExpandFilename but does not expand an empty string to current directory
function SafeExpandFileName (Const FileName : String): String;
// Get application name
function SafeGetApplicationName: String;
// Get application path
function SafeGetApplicationPath: String;
// Get config path
function SafeGetApplicationConfigPath(Global:boolean=false): String;
function SaveFileFromResource(filename,resourcename:string):boolean;
// Copies specified resource (e.g. fpcup.ini, settings.ini)
// to application directory
function SaveInisFromResource(filename,resourcename:string):boolean;
// Searches for SearchFor in the stringlist and returns the index if found; -1 if not
// Search optionally starts from position SearchFor
function StringsStartsWith(const SearchIn:array of string; SearchFor:string; StartIndex:integer=0; CS:boolean=false): integer;
function StringsSame(const SearchIn:array of string; SearchFor:string; StartIndex:integer=0; CS:boolean=false): integer;
function StringListStartsWith(SearchIn:TStringList; SearchFor:string; StartIndex:integer=0; CS:boolean=false): integer;
function StringListEndsWith(SearchIn:TStringList; SearchFor:string; StartIndex:integer=0; CS:boolean=false): integer;
function StringListContains(SearchIn:TStringList; SearchFor:string; StartIndex:integer=0; CS:boolean=false): integer;
function StringListSame(SearchIn:TStringList; SearchFor:string; StartIndex:integer=0; CS:boolean=false): integer;
function GetTotalPhysicalMemory: DWord;
function GetSwapFileSize: DWord;
function XdgConfigHome: String;
{$IFDEF UNIX}
function GetStartupObjects:string;
{$IFDEF LINUX}
function GetFreePhysicalMemory: DWord;
function GetFreeSwapFileSize: DWord;
function IsLinuxMUSL:boolean;
{$ENDIF LINUX}
{$ENDIF UNIX}
function GetLogicalCpuCount: integer;
{$ifdef Darwin}
function GetDarwinSDKVersion(aSDK: string):string;
function GetDarwinSDKLocation:string;
function GetDarwinToolsLocation:string;
function GetXCodeLocation:string;
{$endif}
function GetAndroidSDKDir:string;
function GetAndroidNDKDir:string;
function CompareVersionStrings(s1,s2: string): longint;
function ExistWordInString(const aString:pchar; const aSearchString:string; const aSearchOptions: TStringSearchOptions = []): Boolean;
function UnCamel(const value:string):string;
function GetEnumNameSimple(aTypeInfo:PTypeInfo;const aEnum:integer):string;
function GetEnumValueSimple(aTypeInfo:PTypeInfo;const aEnum:string):integer;
function ContainsDigit(const s: string): Boolean;
//Find a library, if any
function LibWhich(const {%H-}aLibrary: string; out {%H-}dir: string): boolean;
function LibWhich(const aLibrary: string): boolean;
// Emulates/runs which to find executable in path. If not found, returns empty string
function Which(const Executable: string): string;
function IsExecutable(Executable: string):boolean;
function ForceDirectoriesSafe(Const Dir: RawByteString): Boolean;
function CheckExecutable(Executable:string;Parameters:array of string;ExpectOutput: string; beSilent:boolean=false): boolean;
function GetJava: string;
function GetJavac: string;
function CheckJava: boolean;
function ExtractFilePathSafe(const AFilename: string): string;
function ExtractFileNameSafe(const AFilename: string): string;
function FileNameWithoutExt(const AFilename: string): string;
function FileNameWithoutAllExt(const AFilename: string): string;
function FileNameAllExt(const AFilename: string): string;
function DoubleQuoteIfNeeded(s: string): string;
function UppercaseFirstChar(s: String): String;
function DirectoryIsEmpty(Directory: string): Boolean;
function GetTargetCPU:string;
function GetTargetOS:string;
function GetTargetCPUOS:string;
function GetFPCBuildVersion:string;
function GetDistro(const aID:string=''):string;
function GetFreeBSDVersion:byte;
function checkGithubRelease(const aURL:string):string;
{$IF DEFINED(FPC_FULLVERSION) AND (FPC_FULLVERSION < 30200)}
Function Pos(Const Substr : string; Const Source : string; Offset : Sizeint = 1) : SizeInt;
{$ENDIF}
{$IF DEFINED(FPC_FULLVERSION) AND (FPC_FULLVERSION < 30000)}
Function CharInSet(Ch:AnsiChar;Const CSet : TSysCharSet) : Boolean; inline;
{$ENDIF}
function SendMail (Host, Subject, pTo, From, login,password: string; Body: TStrings):boolean;
implementation
uses
{$ifdef LCL}
Forms,//Controls,
{$endif}
{$ifdef Darwin}
MacTypes,
Folders,
Files,
{$endif}
IniFiles,
DOM,DOM_HTML,SAX_HTML,
{$ifdef ENABLENATIVE}
ftpsend,
{$else}
{$IF NOT DEFINED(MORPHOS) AND NOT DEFINED(AROS)}
ftplist,
{$ENDIF}
{$endif}
FileUtil,
LazFileUtils,
{$IF DEFINED(FPC_FULLVERSION) AND (FPC_FULLVERSION >= 30000)}
fpwebclient,
fphttpwebclient,
{$ENDIF}
fpjson, jsonparser ,uriparser
{$IFDEF MSWINDOWS}
//Mostly for shortcut code
,windows, shlobj {for special folders}, ActiveX, ComObj, WinDirs, WinINet
{$ENDIF MSWINDOWS}
{$IFDEF LINUX}
,linux
{$ENDIF}
{$IFDEF UNIX}
,unix,baseunix
{$ENDIF}
{$IFDEF ENABLEWGET}
{$IF NOT DEFINED(MORPHOS) AND NOT DEFINED(AROS) AND NOT DEFINED(AMIGA)}
,fpcuplibcurl
//,libcurl
{$ENDIF}
{$ENDIF ENABLEWGET}
//,SynCrtSock // SendEmail from the mORMot
//,LCLIntf // OpenURL
{$ifndef Haiku}
{$ifdef ENABLEEMAIL}
,mimemess,mimepart,smtpsend
{$endif}
{$endif}
,process
,processutils
,bzip2stream
,DCPdes
,DCPsha256
,NumCPULib in './numcpulib/NumCPULib.pas'
{$IFDEF USEMORMOT}
,mormot.net.client
,mormot.core.buffers
{$ENDIF USEMORMOT}
;
const
NORMALUSERAGENT = 'curl/7.50.1 (i686-pc-linux-gnu) libcurl/7.50.1 OpenSSL/1.0.1t zlib/1.2.8 libidn/1.29 libssh2/1.4.3 librtmp/2.3';
//NORMALUSERAGENT = 'Mozilla/5.0 (compatible; fpweb)';
FPCUPUSERAGENT = 'fpcupdeluxe';
{$IFDEF ENABLEWGET}
CURLUSERAGENT='curl/7.50.1';
//CURLUSERAGENT='curl/7.51.0';
{$ENDIF}
{$IFDEF MSWINDOWS}
WININETUSERAGENT = 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0; WinInet)';
{$ENDIF MSWINDOWS}
{$i revision.inc}
{$ifdef ENABLEEMAIL}
{$i secrets.inc}
{$endif}
type
{$ifdef ENABLENATIVE}
TMyFTPSend = class(TFTPSend);
{$endif ENABLENATIVE}
TOnWriteStream = procedure(Sender: TObject; APos: Int64) of object;
TDownloadStream = class(TFileStream)
private
FStoredTickCount:QWord;
FOnWriteStream: TOnWriteStream;
procedure SetOnWriteStream(aValue:TOnWriteStream);
public
destructor Destroy; override;
function Write(const Buffer; Count: LongInt): LongInt; override;
class function StreamCreate(const aFileName: string; aMode: cardinal):TStream;
published
property OnWriteStream: TOnWriteStream read FOnWriteStream write SetOnWriteStream;
end;
//PTGitHubStore = ^TGitHubStore;
TGitHubStore = record
URL:string;
FileList:TStringList;
end;
TURLDataCache = record
URL:string;
Data:string;
end;
var
GitHubFileListCache:array of TGitHubStore;
URLDataCache:array of TURLDataCache;
function GetStringFromBuffer(const field:PChar):string;
begin
if ( field <> nil ) then
begin
//strpas(field);
result:=field;
UniqueString(result);
SetLength(result,strlen(field));
end else result:='';
end;
function CleanURL(URL:string):string;
const
URLMAGIC='/download';
begin
result:=URL;
if AnsiEndsText(URLMAGIC,URL) then SetLength(result,Length(URL)-Length(URLMAGIC));
end;
(*
function ResNameProc({%H-}ModuleHandle : TFPResourceHMODULE; {%H-}ResourceType, ResourceName : PChar; {%H-}lParam : PtrInt) : LongBool; stdcall;
var
aName:string;
begin
if Assigned(resourcefiles) then
begin
if Is_IntResource(ResourceName)
then aName:=InttoStr({%H-}PtrUInt(ResourceName))
else aName:=GetStringFromBuffer(ResourceName);
resourcefiles.Append(aName);
end;
Result:=true;
end;
function ResTypeProc(ModuleHandle : TFPResourceHMODULE; ResourceType : PChar; lParam : PtrInt) : LongBool; stdcall;
var
aType:string;
RT:integer;
begin
if Is_IntResource(ResourceType) then RT:={%H-}PtrUInt(ResourceType) else
begin
aType:=GetStringFromBuffer(ResourceType);
RT:=StrToIntDef(aType,0);
end;
// get only the plain files (resource type 10; RT_RCDATA)
if RT=10 then EnumResourceNames(ModuleHandle,ResourceType,@ResNameProc,lParam);
Result:=true;
end;
procedure DoEnumResources;
begin
EnumResourceTypes(HINSTANCE,@ResTypeProc,0);
end;
*)
procedure FTPHTMLListingParser(F:TStream;filelist:TStringList);
var
ADoc: THTMLDocument;
HTMFiles : TDOMNodeList;
FilenameValid:boolean;
i,j:integer;
s:string;
FPCSVNList,LAZARUSSVNList:boolean;
begin
FPCSVNList:=False;
LAZARUSSVNList:=False;
F.Position:=0;
try
ReadHTMLFile(ADoc,F);
// a bit rough, but it works
HTMFiles:=ADoc.GetElementsByTagName('title');
if HTMFiles.Count>0 then
begin
s:=HTMFiles[0].TextContent;
FPCSVNList:=(Pos('[fpc]',s)=1);
LAZARUSSVNList:=(Pos('[lazarus]',s)=1);
end;
HTMFiles:=ADoc.GetElementsByTagName('a');
for i:=0 to Pred(HTMFiles.Count) do
begin
s:=TDOMElement(HTMFiles[i]).GetAttribute('name');
if Length(s)>0 then
begin
// validate filename (also rough)
FilenameValid:=True;
for j:=1 to Length(s) do
begin
FilenameValid := (NOT CharInSet(s[j], [';', '=', '+', '<', '>', '|','"', '[', ']', '\', '/', '''']));
if (NOT FilenameValid) then break;
end;
if FilenameValid then
begin
FilenameValid:=False;
FilenameValid:=FilenameValid OR ((LowerCase(ExtractFileExt(s))='.zip') OR (LowerCase(ExtractFileExt(s))='.bz2'));
FilenameValid:=FilenameValid OR ((Pos('lazarus_',s)=1) AND (LAZARUSSVNList));
FilenameValid:=FilenameValid OR ((Pos('release_',s)=1) AND (FPCSVNList));
// finally, add filename if all is ok !!
if FilenameValid then filelist.Add(s);
end;
end;
end;
finally
aDoc.Free;
end;
end;
{$ifdef mswindows}
function GetWin32Version(out Major,Minor,Build : Integer): Boolean;
var
Info: TOSVersionInfo;
begin
Info.dwOSVersionInfoSize := SizeOf(Info);
if GetVersionEx(Info) then
begin
with Info do
begin
Win32Platform:=dwPlatformId;
Major:=dwMajorVersion;
Minor:=dwMinorVersion;
Build:=dwBuildNumber;
result:=true
end;
end
else result:=false;
end;
function CheckWin32Version(aMajor,aMinor: Integer): Boolean;
var
Major,Minor,Build : Integer;
begin
if GetWin32Version(Major,Minor,Build) then
begin
result:=(Major>aMajor) or
((Major=aMajor) and (Minor>=aMinor));
end else result:=false;
end;
function IsWindows64: boolean;
{
Detect if we are running on 64 bit Windows or 32 bit Windows,
independently of bitness of this program.
Original source:
http://www.delphipraxis.net/118485-ermitteln-ob-32-bit-oder-64-bit-betriebssystem.html
modified for FreePascal in German Lazarus forum:
http://www.lazarusforum.de/viewtopic.php?f=55&t=5287
}
{$ifdef WIN32} //Modified KpjComp for 64bit compile mode
type
TIsWow64Process = function( // Type of IsWow64Process API fn
Handle: Windows.THandle; var Res: Windows.BOOL): Windows.BOOL; stdcall;
var
IsWow64Result: Windows.BOOL; // Result from IsWow64Process
IsWow64Process: TIsWow64Process; // IsWow64Process fn reference
begin
// Try to load required function from kernel32
IsWow64Process := TIsWow64Process(Windows.GetProcAddress(
Windows.GetModuleHandle('kernel32'), 'IsWow64Process'));
if Assigned(IsWow64Process) then
begin
// Function is implemented: call it
if not IsWow64Process(Windows.GetCurrentProcess, IsWow64Result) then
raise SysUtils.Exception.Create('IsWindows64: bad process handle');
// Return result of function
Result := IsWow64Result;
end
else
// Function not implemented: can't be running on Wow64
Result := False;
{$else} //if were running 64bit code, OS must be 64bit :)
begin
Result := True;
{$endif}
end;
{$endif}
function MulDiv( a, b, c : Integer ) : Integer;
begin
result := int64(a)*int64(b) div c;
end;
function SafeExpandFileName (Const FileName : String): String;
begin
if FileName='' then
result:=''
else
result:=ExpandFileName(FileName);
end;
function SafeGetApplicationName: String;
var
StartPath: String;
{$ifdef Darwin}
x:integer;
{$endif}
begin
{$ifdef LCL}
StartPath:=Application.ExeName;
{$else}
StartPath:=Paramstr(0);
{$endif}
{$ifdef Darwin}
// we need the .app itself !!
x:=pos('/Contents/MacOS',StartPath);
if x>0 then
begin
Delete(StartPath,x,MaxInt);
(*
x:=RPos('/',StartPath);
if x>0 then
begin
Delete(StartPath,x+1,MaxInt);
end;
*)
end;
{$endif}
if FileIsSymlink(StartPath) then
begin
try
StartPath:=GetPhysicalFilename(StartPath,pfeException);
except
end;
end;
result:=StartPath;
end;
function SafeGetApplicationPath: String;
var
StartPath: String;
begin
StartPath:=ExtractFileDir(SafeGetApplicationName);
(*
//StartPath:=IncludeTrailingPathDelimiter(ProgramDirectory);
StartPath:=Application.Location;
{$ifdef Darwin}
// do not store settings inside app iself ...
// not necessary the right choice ... ;-)
x:=pos('/Contents/MacOS',StartPath);
if x>0 then
begin
Delete(StartPath,x,MaxInt);
x:=RPos('/',StartPath);
if x>0 then
begin
Delete(StartPath,x+1,MaxInt);
end;
end;
{$endif}
if FileIsSymlink(StartPath) then
StartPath:=GetPhysicalFilename(StartPath,pfeException);
result:=ExtractFilePath(StartPath);
*)
if DirectoryExists(StartPath) then
begin
try
StartPath:=GetPhysicalFilename(StartPath,pfeException);
except
end;
end;
result:=IncludeTrailingPathDelimiter(StartPath);
end;
function SafeGetApplicationConfigPath(Global:boolean=false): String;
{$IFDEF DARWIN}
const
kMaxPath = 1024;
var
theError: OSErr;
theRef: FSRef;
pathBuffer: PChar;
{$ENDIF}
begin
result:='';
{$IFDEF DARWIN}
theRef := Default(FSRef); // init
try
pathBuffer := Allocmem(kMaxPath);
except on exception
do exit;
end;
try
Fillchar(pathBuffer^, kMaxPath, #0);
Fillchar(theRef, Sizeof(theRef), #0);
if Global then // kLocalDomain
theError := FSFindFolder(kLocalDomain, kPreferencesFolderType, kDontCreateFolder, theRef)
else // kUserDomain
theError := FSFindFolder(kUserDomain , kPreferencesFolderType, kDontCreateFolder, theRef);
if (pathBuffer <> nil) and (theError = noErr) then
begin
theError := FSRefMakePath(theRef, pathBuffer, kMaxPath);
if theError = noErr then
result := UTF8ToAnsi(StrPas(pathBuffer));
end;
finally
Freemem(pathBuffer);
end;
{$ELSE}
{$IFDEF MSWINDOWS}
if Global then
result:=GetWindowsSpecialDir(CSIDL_COMMON_APPDATA)
else
result:=GetWindowsSpecialDir(CSIDL_LOCAL_APPDATA);
{$ELSE}
if Global then
result:=SysConfigDir
else
begin
result:=SysUtils.GetEnvironmentVariable('HOME');
if (result='') then
result:=SafeExpandFileName(IncludeTrailingPathDelimiter(GetUserDir)+'.config')
else
result:=IncludeTrailingPathDelimiter(result) + '.config';
end;
{$ENDIF}
{$ENDIF}
result:=IncludeTrailingPathDelimiter(result);
end;
function SafeGetApplicationTempPath(Global:boolean=false): String;
{$IFDEF DARWIN}
const
kMaxPath = 1024;
var
theError: OSErr;
theRef: FSRef;
pathBuffer: PChar;
{$ENDIF}
begin
result:='';
{$IFDEF DARWIN}
theRef := Default(FSRef); // init
try
pathBuffer := Allocmem(kMaxPath);
except on exception
do exit;
end;
try
Fillchar(pathBuffer^, kMaxPath, #0);
Fillchar(theRef, Sizeof(theRef), #0);
if Global then // kLocalDomain
theError := FSFindFolder(kLocalDomain, kTemporaryFolderType, kDontCreateFolder, theRef)
else // kUserDomain
theError := FSFindFolder(kUserDomain , kTemporaryFolderType, kDontCreateFolder, theRef);
if (pathBuffer <> nil) and (theError = noErr) then
begin
theError := FSRefMakePath(theRef, pathBuffer, kMaxPath);
if theError = noErr then
result := UTF8ToAnsi(StrPas(pathBuffer));
end;
finally
Freemem(pathBuffer);
end;
{$ELSE}
{$IFDEF MSWINDOWS}
if Global then
result:=GetWindowsSpecialDir(CSIDL_COMMON_APPDATA)
else
result:=GetWindowsSpecialDir(CSIDL_LOCAL_APPDATA);
{$ELSE}
if Global then
result:=SysConfigDir
else
begin
result:=SysUtils.GetEnvironmentVariable('HOME');
if (result='') then
result:=SafeExpandFileName(IncludeTrailingPathDelimiter(GetUserDir)+'.cache')
else
result:=IncludeTrailingPathDelimiter(result) + '.cache';
end;
{$ENDIF}
{$ENDIF}
result:=IncludeTrailingPathDelimiter(result);
end;
function SaveFileFromResource(filename,resourcename:string):boolean;
var
fs:Tfilestream;
begin
result:=false;
if FileExists(filename) then SysUtils.DeleteFile(filename);
with TResourceStream.Create(hInstance, resourcename, RT_RCDATA) do
try
try
fs:=Tfilestream.Create(filename,fmCreate);
Savetostream(fs);
finally
fs.Free;
end;
finally
Free;
end;
result:=FileExists(filename);
end;
function SaveInisFromResource(filename,resourcename:string):boolean;
var
fs:Tfilestream;
ms:TMemoryStream;
BackupFileName:string;
{$IF DEFINED(FPC_FULLVERSION) AND (FPC_FULLVERSION > 30000)}
Ini:TMemIniFile;
{$ELSE}
Ini:TIniFile;
{$ENDIF}
OldIniVersion,NewIniVersion:string;
Major,Minor,Build,Patch: Integer;
OldIniVersionNum,NewIniVersionNum:qword;
begin
result:=false;
if NOT FileExists(filename) then
begin
result:=SaveFileFromResource(filename,resourcename);
end
else
begin
// create memory stream of resource
ms:=TMemoryStream.Create;
try
with TResourceStream.Create(hInstance, resourcename, RT_RCDATA) do
try
Savetostream(ms);
finally
Free;
end;
ms.Position:=0;
{$IF DEFINED(FPC_FULLVERSION) AND (FPC_FULLVERSION > 30000)}
Ini:=TMemIniFile.Create(ms);
{$ELSE}
Ini:=TIniFile.Create(ms);
{$ENDIF}
{$IF DEFINED(FPC_FULLVERSION) AND (FPC_FULLVERSION > 30000)}
Ini.Options:=[ifoStripQuotes];
{$ELSE}
ini.StripQuotes:=true;
{$ENDIF}
NewIniVersion:=Ini.ReadString('fpcupinfo','inifileversion','0.0.0.0');
Ini.Free;
Ini:=TMemIniFile.Create(filename);
{$IF DEFINED(FPC_FULLVERSION) AND (FPC_FULLVERSION > 30000)}
Ini.Options:=[ifoStripQuotes];
{$ELSE}
ini.StripQuotes:=true;
{$ENDIF}
OldIniVersion:=Ini.ReadString('fpcupinfo','inifileversion','0.0.0.0');
Ini.Free;
Major:=0;
Minor:=0;
Build:=0;
Patch:=0;
VersionFromString(OldIniVersion,Major,Minor,Build,Patch);
OldIniVersionNum:=CalculateFullVersion(Major,Minor,Build,Patch);
Major:=0;
Minor:=0;
Build:=0;
Patch:=0;
VersionFromString(NewIniVersion,Major,Minor,Build,Patch);
NewIniVersionNum:=CalculateFullVersion(Major,Minor,Build,Patch);
if (NewIniVersionNum>OldIniVersionNum) then
begin
BackupFileName:=ChangeFileExt(filename,'.bak');
while FileExists(BackupFileName) do BackupFileName := BackupFileName + 'k';
FileUtil.CopyFile(filename,BackupFileName);
if SysUtils.DeleteFile(filename) then
begin
ms.Position:=0;
fs := TFileStream.Create(filename,fmCreate);
try
fs.CopyFrom(ms, ms.Size);
finally
FreeAndNil(fs);
end;
end;
end;
finally
ms.Free;
end;
end;
result:=FileExists(filename);
end;
{$IFDEF MSWINDOWS}
procedure CreateDesktopShortCut(Target, TargetArguments, ShortcutName: string; AddContext:boolean=false);
var
IObject: IUnknown;
ISLink: IShellLink;
IPFile: IPersistFile;
PIDL: PItemIDList;