-
Notifications
You must be signed in to change notification settings - Fork 42
/
xidelbase.pas
4417 lines (3862 loc) · 160 KB
/
xidelbase.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) 2012 - 2019 Benito van der Zander (BeniBela)
www.benibela.de
This program 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 3 of the License, or
(at your option) any later 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
}
unit xidelbase;
{$mode objfpc}{$H+}
{$modeswitch advancedrecords}
{$modeswitch typehelpers}
{$COperators on}{$goto on}{$inline on}
//{$define FREE_ALL_MEMORY_ON_EXIT}
interface
uses
Classes, {$ifdef windows} windows, {$endif}
extendedhtmlparser, xquery, sysutils, bbutils, simplehtmltreeparser, multipagetemplate,
internetaccess, contnrs, simplexmltreeparserfpdom,
xquery_module_file,
//xquery_module_binary,
xquery_module_math,
xquery_module_uca_icu,
internetaccess_inflater_paszlib,
rcmdline,math
;
var cgimode: boolean = false;
allowInternetAccess: boolean = true;
xqueryDefaultCollation: string = '';
mycmdline: TCommandLineReader;
defaultUserAgent: string = 'Mozilla/5.0 (compatible; Xidel)';
majorVersion: integer = 0;
minorVersion: integer = 9;
buildVersion: integer = 9;
var
onPostParseCmdLine: procedure ();
onRetrieve: function (const method, url, postdata, headers: string): string;
onPreOutput: procedure (extractionKind: TExtractionKind);
procedure perform;
implementation
uses process, strutils, bigdecimalmath, xquery_json, xquery__regex, xquery.internals.common, xquery.namespaces, xidelcrt,
xquery__serialization, xquery__serialization_nodes, fastjsonreader;
//{$R xidelbase.res}
///////////////LCL IMPORT
//uses lazutf8;
{$ifdef windows}
function WinCPToUTF8(const s: string): string; {$ifdef WinCe}inline;{$endif}
// result has codepage CP_ACP
var
UTF16WordCnt: SizeInt;
UTF16Str: UnicodeString;
begin
{$ifdef WinCE}
Result := SysToUtf8(s);
{$else}
Result:=s;(*
if IsASCII(Result) then begin
{$ifdef FPC_HAS_CPSTRING}
// prevent codepage conversion magic
SetCodePage(RawByteString(Result), CP_ACP, False);
{$endif}
exit;
end; *)
UTF16WordCnt:=MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, Pointer(s), length(s), nil, 0);
// this will null-terminate
if UTF16WordCnt>0 then
begin
setlength(UTF16Str, UTF16WordCnt);
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, Pointer(s), length(s), @UTF16Str[1], UTF16WordCnt);
Result:=UTF8Encode(UTF16Str);
{$ifdef FPC_HAS_CPSTRING}
// prevent codepage conversion magic
SetCodePage(system.RawByteString(Result), CP_ACP, False);
{$endif}
end;
{$endif}
end;
function ConsoleToUTF8(const s: string): string;// converts UTF8 string to console encoding (used by Write, WriteLn)
{$ifNdef WinCE}
var
Dst: PChar;
{$endif}
begin
{$ifdef WinCE}
Result := SysToUTF8(s);
{$else}
Dst := AllocMem((Length(s) + 1) * SizeOf(Char));
if OemToChar(PChar(s), Dst) then
Result := StrPas(Dst)
else
Result := s;
FreeMem(Dst);
Result := WinCPToUTF8(Result);
{$endif}
end;
(*
function UTF8ToConsole(const s: string): string;
{$ifNdef WinCE}
var
Dst: PChar;
{$endif}
begin
{$ifdef WinCE}
Result := UTF8ToSys(s);
{$else WinCE}
{$ifndef NO_CP_RTL}
Result := UTF8ToWinCP(s);
{$else NO_CP_RTL}
Result := UTF8ToSys(s); // Kept for compatibility
{$endif NO_CP_RTL}
Dst := AllocMem((Length(Result) + 1) * SizeOf(Char));
if CharToOEM(PChar(Result), Dst) then
Result := StrPas(Dst);
FreeMem(Dst);
{$ifndef NO_CP_RTL}
SetCodePage(RawByteString(Result), CP_OEMCP, False);
{$endif NO_CP_RTL}
{$endif WinCE}
end;*)
{$endif}
function GetEnvironmentVariableUTF8(const EnvVar: string): String;
begin
{$IFDEF FPC_RTL_UNICODE}
Result:=UTF16ToUTF8(SysUtils.GetEnvironmentVariable(UTF8ToUTF16(EnvVar)));
{$ELSE}
// on Windows SysUtils.GetEnvironmentString returns OEM encoded string
// so ConsoleToUTF8 function should be used!
// RTL issue: http://bugs.freepascal.org/view.php?id=15233
Result:={$ifdef windows}ConsoleToUTF8{$endif}(SysUtils.GetEnvironmentVariable({UTF8ToSys}(EnvVar)));
{$ENDIF}
end;
/////////////////////////////////////////////////////
function internet: TInternetAccess;
begin
if not allowInternetAccess then raise EXidelException.Create('Internet access not permitted');
result := defaultInternet;
end;
type TInputFormat = (ifAuto, ifXML, ifHTML, ifXMLStrict, ifJSON, ifJSONStrict, ifPlainText);
var
globalDefaultInputFormat: TInputFormat;
type
IData = interface //data interface, so we do not have to care about memory managment
function rawData: string;
function baseUri: string;
function displayBaseUri: string;
function contenttype: string;
function headers: THTTPHeaderList;
function recursionLevel: integer;
function inputFormat: TInputFormat;
end;
{ THtmlTemplateParserBreaker }
THtmlTemplateParserBreaker = class(THtmlTemplateParser)
ignorenamespaces: boolean;
procedure initParsingModel(const data: IData);
procedure parseHTML(const data: IData);
procedure parseHTMLSimple(const data: IData);
procedure closeVariableLog;
procedure parseDoc({%H-}sender: TXQueryEngine; html,uri,contenttype: string; var node: TTreeNode);
end;
{ TTemplateReaderBreaker }
TTemplateReaderBreaker = class(TMultipageTemplateReader)
constructor create();
destructor destroy(); override;
procedure setTemplate(atemplate: TMultiPageTemplate);
procedure perform(actions: TStringArray);
procedure selfLog({%H-}sender: TMultipageTemplateReader; logged: string; debugLevel: integer);
end;
//data processing classes
var htmlparser:THtmlTemplateParserBreaker;
xpathparser: TXQueryEngine;
multipage: TTemplateReaderBreaker;
multipagetemp: TMultiPageTemplate;
currentRoot: TTreeNode = nil;
var firstGroup: boolean = true;
procedure writeBeginGroup;
begin
case outputFormat of
ofXMLWrapped: begin
wcolor('<e>', cXML);
end;
ofJsonWrapped: if not firstGroup then wcolor(', ' + LineEnding, cJSON);
else ;
end;
firstGroup := false;
end;
procedure writeEndGroup;
begin
case outputFormat of
ofXMLWrapped: begin
wcolor('</e>' + LineEnding, cXML);
end;
else ;
end;
end;
{procedure printBeginValueGroup;
begin
end;
procedure printBeginValue(varname: string);
begin
case outputFormat of
ofXMLWrapped: w('<e>');
end;
firstValue := false;
end;
procedure printInnerValueSeparator;
begin
if not firstValue then begin
w(outputSeparator);
//w(outputArraySeparator[outputFormat]);
end;
firstValue := false;
end;
procedure printEndValue;
begin
end;
procedure printEndValueGroup;
begin
end; }
function joined(s: array of string): string; //for command line help
var
i: Integer;
begin
if length(s) = 0 then exit('');
result := s[0];
for i:=1 to high(s) do result := result + LineEnding + s[i];
end;
function strLoadFromFileChecked(const fn: string): string;
begin
result := strLoadFromFileUTF8(fn);
if strBeginsWith(result, '#!') then result := strAfter(result, #10);
if Result = '' then raise EXidelException.Create('File '+fn+' is empty.');
end;
type
trilean = (tUnknown, tTrue, tFalse);
{ TOptionReaderWrapper }
TOptionReaderWrapper = class
function read(const name: string; var value: string): boolean; virtual; abstract; //must be out since it is used to clear some values in --follow requests
function read(const name: string; var value: integer): boolean; virtual; abstract;
function read(const name: string; var value: boolean): boolean; virtual; abstract;
function read(const name: string; var value: Extended): boolean; virtual; abstract;
function read(const name: string; var value: IXQValue): boolean; virtual;
function read(const name: string; var inputformat: TInputFormat): boolean; virtual;
function read(const name: string; var value: trilean): boolean; virtual;
end;
{ TOptionReaderFromCommandLine }
TOptionReaderFromCommandLine = class(TOptionReaderWrapper)
constructor create(cmdLine: TCommandLineReader);
function read(const name: string; var value: string): boolean; override;
function read(const name: string; var value: integer): boolean; override;
function read(const name: string; var value: boolean): boolean; override;
function read(const name: string; var value: Extended): boolean; override;
private
acmdLine: TCommandLineReader;
end;
{ TOptionReaderFromObject }
TOptionReaderFromObject = class(TOptionReaderWrapper)
constructor create(aobj: TXQBoxedMapLike);
function read(const name: string; var value: string): boolean; override;
function read(const name: string; var value: integer): boolean; override;
function read(const name: string; var value: boolean): boolean; override;
function read(const name: string; var value: Extended): boolean; override;
function read(const name: string; var value: IXQValue): boolean; override;
private
obj: TXQBoxedMapLike;
end;
type
{ TData }
{ TDataObject }
TDataObject = class(TInterfacedObject, IData)
{private todo: optimize
fparsed: TTreeDocument;
function GetParsed: TTreeDocument;
public}
private
frawdata: string;
fbaseurl, fdisplaybaseurl: string;
fcontenttype: string;
frecursionLevel: integer;
finputformat: TInputFormat;
fheaders: THTTPHeaderList;
public
function rawData: string;
function baseUri: string;
function displayBaseUri: string;
function contentType: string;
function headers: THTTPHeaderList;
function recursionLevel: integer;
function inputFormat: TInputFormat;
constructor create(somedata: string; aurl: string; acontenttype: string = '');
destructor Destroy; override;
//property parsed:TTreeDocument read GetParsed;
end;
TDataProcessing = class;
TProcessingContext = class;
{ TFollowTo }
TFollowTo = class
nextAction: integer; //the next action after the action yielding the data, so an action does not process its own follows
inputFormat: TInputFormat;
class function createFromRetrievalAddress(data: string): TFollowTo;
function clone: TFollowTo; virtual; abstract;
function retrieve(parent: TProcessingContext; arecursionLevel: integer): IData; virtual; abstract;
procedure replaceVariables; virtual;
function equalTo(ft: TFollowTo): boolean; virtual; abstract;
procedure readOptions(reader: TOptionReaderWrapper); virtual;
procedure assign(other: TFollowTo); virtual;
end;
{ THTTPRequest }
THTTPRequest = class(TFollowTo)
private
variablesReplaced: boolean;
public
url: string;
method: string;
data: string;
header: string;
multipart: string;
rawURL: boolean;
constructor create(aurl: string);
function clone: TFollowTo; override;
function retrieve(parent: TProcessingContext; arecursionLevel: integer): IData; override;
procedure replaceVariables; override;
function equalTo(ft: TFollowTo): boolean; override;
procedure readOptions(reader: TOptionReaderWrapper); override;
end;
{ TFileRequest }
TFileRequest = class(TFollowTo)
url: string;
constructor create(aurl: string);
function clone: TFollowTo; override;
function retrieve(parent: TProcessingContext; arecursionLevel: integer): IData; override;
procedure replaceVariables; override;
function equalTo(ft: TFollowTo): boolean; override;
end;
{ TDirectDataRequest }
TDirectDataRequest = class(TFollowTo)
data: string;
constructor create(adata: string);
function clone: TFollowTo; override;
function retrieve({%H-}parent: TProcessingContext; arecursionLevel: integer): IData; override;
function equalTo(ft: TFollowTo): boolean; override;
//procedure replaceVariables; do not replace vars in direct data
end;
{ TStdinDataRequest }
TStdinDataRequest = class(TFollowTo)
function clone: TFollowTo; override;
function retrieve({%H-}parent: TProcessingContext; arecursionLevel: integer): IData; override;
function equalTo(ft: TFollowTo): boolean; override;
end;
{ TFollowToProcessedData }
TFollowToProcessedData = class(TFollowTo)
data: IData;
constructor create(d: IData);
function clone: TFollowTo; override;
function retrieve({%H-}parent: TProcessingContext; arecursionLevel: integer): IData; override;
function equalTo(ft: TFollowTo): boolean; override;
end;
TFollowToXQVObject = class(TFollowTo)
v: IXQValue;
basedata: IData;
constructor create(const abasedata: IData; const av: IXQValue);
function clone: TFollowTo; override;
function retrieve(parent: TProcessingContext; arecursionLevel: integer): IData; override;
function equalTo(ft: TFollowTo): boolean; override;
end;
{TFollowXQV = class(TFollowTo)
xqv: TXQValue;
//can be url/http-request, file(?), data
//object with arbitrary options
//sequence of previous
end;}
{ TFollowToList }
TFollowToList = class(TFpObjectList)
constructor Create;
procedure merge(l: TFollowToList; nextAction: integer = 0);
function first: TFollowTo;
procedure add(ft: TFollowTo);
procedure merge(dest: IXQValue; basedata: IData; parent: TProcessingContext);
function containsEqual(ft: TFollowTo): boolean;
private
procedure addBasicUrl(absurl: string; baseurl: string; inputFormat: TInputFormat);
procedure addObject(absurl: string; baseurl: string; options: TXQBoxedMapLike; fallBackInputFormat: TInputFormat);
end;
{ TDataProcessing }
TDataProcessing = class
parent: TProcessingContext;
function process(data: IData): TFollowToList; virtual; abstract;
procedure readOptions({%H-}reader: TOptionReaderWrapper); virtual;
procedure initFromCommandLine(cmdLine: TCommandLineReader); virtual;
procedure mergeWithObject(obj: TXQBoxedMapLike); virtual;
function clone(newparent: TProcessingContext): TDataProcessing; virtual; abstract;
end;
{ TDownload }
TDownload = class(TDataProcessing)
downloadTarget: string;
function process(data: IData): TFollowToList; override;
procedure readOptions(reader: TOptionReaderWrapper); override;
function clone(newparent: TProcessingContext): TDataProcessing; override;
end;
{ TExtraction }
TExtraction = class(TDataProcessing)
extract: string;
extractQueryCache: IXQuery;
extractExclude, extractInclude: TStringArray;
extractKind: TExtractionKind;
extractBaseUri: string;
templateActions: TStringArray;
defaultName: string;
printVariables: set of (pvLog, pvCondensedLog, pvFinal);
printTypeAnnotations, hideVariableNames: boolean;
printedNodeFormat: TTreeNodeSerialization;
printedJSONFormat: (jisDefault, jisPretty, jisCompact);
printedJSONKeyOrder: TXQKeyOrder;
outputIndentXML, inplaceOverride: boolean;
inputFormat: TInputFormat;
constructor create;
procedure readOptions(reader: TOptionReaderWrapper); override;
procedure setVariables(v: string);
procedure printExtractedValue(value: IXQValue; invariable: boolean);
procedure printCmdlineVariable(const name: string; const value: IXQValue);
procedure printExtractedVariables(vars: TXQVariableChangeLog; state: string; showDefaultVariable: boolean);
procedure printExtractedVariables(parser: THtmlTemplateParser; showDefaultVariableOverride: boolean);
function process(data: IData): TFollowToList; override;
procedure assignOptions(other: TExtraction);
function clone(newparent: TProcessingContext): TDataProcessing; override;
private
currentFollowList: TFollowToList;
currentData: IData;
procedure pageProcessed({%H-}unused: TMultipageTemplateReader; parser: THtmlTemplateParser);
procedure prepareForOutput(const data: IData);
end;
{ TFollowToWrapper }
TFollowToWrapper = class(TDataProcessing)
followTo: TFollowTo;
procedure readOptions(reader: TOptionReaderWrapper); override;
function process(data: IData): TFollowToList; override;
function clone(newparent: TProcessingContext): TDataProcessing; override;
destructor Destroy; override;
end;
{ TProcessingContext }
TXQueryCompatibilityOptions = record
JSONMode: (cjmUndefined, cjmUnified, cjmStandard, cjmJSONiq, cjmDeprecated);
noExtendedStrings, noJSON, noJSONliterals, onlyJSONObjects, noExtendedJson, strictTypeChecking, strictNamespaces: trilean;
dotNotation: TXQPropertyDotNotation;
ignoreNamespace: boolean;
procedure setUnknownToDefault(kind: TExtractionKind);
procedure configureParsers;
procedure configureParsers(kind: TExtractionKind);
end;
TStatusInfo = (sDefault, sProcessingInformation);
//Processing is done in processing contexts
//A processing context can have its own data sources (TFollowTo or data sources of a nested processing context) or receive the data from its parent
//To every data source actions are applied (e.g. tdownload or textraction). These actions can also yield new data sources (e.g. follow := assignments or nested processing contexts with yieldDataToParent)
//The expression in follow is evaluated and the resulting data processed in the context followTo
//Then processing continues in nextSibling
//Remaining unprocessed data is passed to the parent
TProcessingContext = class(TDataProcessing)
dataSources: array of TDataProcessing; //data sources, e.g. a list of URLs
actions: array of TDataProcessing; //actions e.g. a download target
follow: string;
followKind: TExtractionKind;
followQueryCache: IXQuery;
followExclude, followInclude: TStringArray;
followTo: TProcessingContext;
followMaxLevel: integer;
followInputFormat: TInputFormat;
nextSibling: TProcessingContext;
wait: Extended;
userAgent: string;
proxy: string;
hasProxySettings: boolean;
printReceivedHeaders: boolean;
errorHandling: string;
loadCookies, saveCookies: string;
silent, printPostData: boolean;
compatibility: TXQueryCompatibilityOptions;
noOptimizations: boolean;
yieldDataToParent: boolean;
procedure configureInternet;
procedure printStatus(header, status: string; statusInfo: TStatusInfo);
procedure readOptions(reader: TOptionReaderWrapper); override;
procedure mergeWithObject(obj: TXQBoxedMapLike); override;
procedure addNewDataSource(source: TDataProcessing);
procedure readNewDataSource(data: TFollowTo; options: TOptionReaderWrapper);
procedure addNewAction(action: TDataProcessing);
procedure readNewAction(action: TDataProcessing; options: TOptionReaderWrapper);
procedure assignOptions(other: TProcessingContext);
procedure assignActions(other: TProcessingContext);
function clone(newparent: TProcessingContext): TDataProcessing; override;
function last: TProcessingContext; //returns the last context in this sibling/follow chain
procedure insertFictiveDatasourceIfNeeded(canUseStdin: boolean; options: TOptionReaderWrapper); //if no data source is given in an expression (or an subexpression), but an aciton is there, <empty/> is added as data source
function process(data: IData): TFollowToList; override;
class function replaceEnclosedExpressions(expr: string): string;
function replaceEnclosedExpressions(data: IData; expr: string): string;
destructor destroy; override;
private
stupidHTTPReactionHackFlag: integer;
procedure loadDataForQueryPreParse(const data: IData);
procedure loadDataForQuery(const data: IData; const query: IXQuery);
function evaluateQuery(const query: IXQuery; const data: IData; const allowWithoutReturnValue: boolean = false): IXQValue;
procedure httpReact (sender: TInternetAccess; var {%H-}transfer: TTransfer; var reaction: TInternetAccessReaction);
end;
var globalCurrentExtraction: TExtraction;
type EInvalidArgument = Exception;
var GlobalJSONParseOptions: TJSONParserOptions = [];
procedure setJSONFormat(format: TInputFormat);
begin
case format of //todo: cache?
ifJSON: xpathparser.DefaultJSONParser.options := [jpoAllowMultipleTopLevelItems, jpoLiberal, jpoAllowTrailingComma] + GlobalJSONParseOptions;
ifJSONStrict: xpathparser.DefaultJSONParser.options := [] + GlobalJSONParseOptions;
else;
end;
end;
procedure TXQueryCompatibilityOptions.setUnknownToDefault(kind: TExtractionKind);
begin
if noJSON = tUnknown then noJSON := tFalse;
case kind of
ekPatternXML, ekPatternHTML, ekMultipage, ekDefault: begin
if JSONMode = cjmUndefined then JSONMode := cjmUnified;
if noExtendedStrings = tUnknown then noExtendedStrings := tFalse;
if noJSONliterals = tUnknown then begin
if JSONMode = cjmStandard then noJSONliterals := ttrue
else noJSONliterals:=tFalse;
end;
if onlyJSONObjects = tUnknown then onlyJSONObjects := tFalse;
if noExtendedJson = tUnknown then
if JSONMode in [cjmStandard,cjmJSONiq] then noExtendedJson := tTrue
else noExtendedJson := tFalse;
if strictTypeChecking = tUnknown then strictTypeChecking := tFalse;
if strictNamespaces = tUnknown then strictNamespaces := tFalse;
if dotNotation = xqpdnUndefined then dotNotation := xqpdnAllowUnambiguousDotNotation;
end;
else begin
if JSONMode = cjmUndefined then JSONMode := cjmStandard;
if noExtendedStrings = tUnknown then noExtendedStrings := tTrue;
if noJSONliterals = tUnknown then noJSONliterals:=tTrue;
if onlyJSONObjects = tUnknown then onlyJSONObjects := tFalse;
if noExtendedJson = tUnknown then noExtendedJson := tTrue;
if strictTypeChecking = tUnknown then strictTypeChecking := tTrue;
if strictNamespaces = tUnknown then strictNamespaces := tTrue;
if dotNotation = xqpdnUndefined then dotNotation := xqpdnDisallowDotNotation;
end;
end;
end;
procedure TXQueryCompatibilityOptions.configureParsers;
begin
xpathparser.ParsingOptions.AllowExtendedStrings := NoExtendedStrings = tFalse;
xpathparser.ParsingOptions.AllowJSONLiterals := NoJSONliterals = tFalse;
xpathparser.ParsingOptions.AllowPropertyDotNotation:=DotNotation;
case JSONMode of
cjmDeprecated: begin
xpathparser.ParsingOptions.AllowJSON:=NoJSON = tfalse;
if (NoJSON = tfalse) and (OnlyJSONObjects = tTrue) then begin
xpathparser.ParsingOptions.JSONArrayMode := xqjamJSONiq;
xpathparser.ParsingOptions.JSONObjectMode := xqjomJSONiq;
end;
GlobalJSONParseOptions := [jpoJSONiq];
xpathparser.StaticContext.AllowJSONiqOperations := true;
end;
cjmStandard: begin
xpathparser.ParsingOptions.JSONArrayMode := xqjamStandard;
xpathparser.ParsingOptions.JSONObjectMode := xqjomForbidden;
xpathparser.ParsingOptions.AllowJSONiqTests := false;
xpathparser.StaticContext.AllowJSONiqOperations := false;
end;
cjmJSONiq: begin
xpathparser.ParsingOptions.JSONArrayMode := xqjamJSONiq;
xpathparser.ParsingOptions.JSONObjectMode := xqjomJSONiq;
xpathparser.ParsingOptions.AllowJSONiqTests := true;
GlobalJSONParseOptions := [jpoJSONiq];
xpathparser.StaticContext.AllowJSONiqOperations := true;
end;
cjmUnified: begin
xpathparser.ParsingOptions.JSONArrayMode := xqjamStandard;
xpathparser.ParsingOptions.JSONObjectMode := xqjomMapAlias;
xpathparser.ParsingOptions.AllowJSONiqTests := true;
xpathparser.StaticContext.AllowJSONiqOperations := false;
end;
end;
setJSONFormat(globalDefaultInputFormat);
xpathparser.StaticContext.jsonPXPExtensions:=NoExtendedJson = tFalse;
xpathparser.StaticContext.strictTypeChecking:=StrictTypeChecking = tTrue;
xpathparser.StaticContext.useLocalNamespaces:=StrictNamespaces = tFalse;
htmlparser.ignoreNamespaces := ignoreNamespace;
end;
procedure TXQueryCompatibilityOptions.configureParsers(kind: TExtractionKind);
var mycopy: TXQueryCompatibilityOptions;
begin
mycopy := self;
mycopy.setUnknownToDefault(kind);
mycopy.configureParsers();
case kind of
ekAuto: ;
ekPatternHTML, ekPatternXML: begin
if kind = ekPatternHTML then htmlparser.TemplateParser.parsingModel := pmHTML
else htmlparser.TemplateParser.parsingModel := pmStrict;
htmlparser.QueryEngine.ParsingOptions.StringEntities:=xqseIgnoreLikeXPath;
end;
ekDefault: begin
xpathparser.ParsingOptions.StringEntities:=xqseResolveLikeXQueryButIgnoreInvalid
end;
ekXPath2, ekXPath3_0, ekXPath3_1, ekXPath4_0, ekCSS, ekXQuery1, ekXQuery3_0, ekXQuery3_1, ekXQuery4_0: begin
xpathparser.ParsingOptions.StringEntities:=xqseDefault;
end;
ekMultipage: ;
end;
end;
constructor TFollowToXQVObject.create(const abasedata: IData; const av: IXQValue);
begin
basedata := abasedata;
v := av;
end;
function TFollowToXQVObject.clone: TFollowTo;
begin
result := TFollowToXQVObject.create(basedata, v);
end;
function TFollowToXQVObject.retrieve(parent: TProcessingContext; arecursionLevel: integer): IData;
var
temp: TProcessingContext;
fl: TFollowToList;
begin
result := nil;
if parent = nil then exit();
temp := TProcessingContext.Create();
fl := TFollowToList.Create;
temp.assignOptions(parent); //do not copy actions/data sources. they would apply to basedata, not to dest
temp.parent := parent;
temp.follow := parent.follow; //need to copy follow and follow-to, so it follows to the new data
temp.followKind := parent.followKind;
temp.followTo := parent.followTo;
temp.followInputFormat := parent.followInputFormat;
temp.nextSibling := parent.nextSibling;
temp.mergeWithObject(v.toMap);
fl := temp.process(basedata);
case fl.count of
0: ;
1: result := fl.first.retrieve(temp, arecursionLevel );
else raise Exception.Create('Invalid follow to count: ' + inttostr(fl.Count));
end;
temp.followTo := nil;
temp.nextSibling := nil;
temp.Free;
end;
function TFollowToXQVObject.equalTo(ft: TFollowTo): boolean;
begin
if not (ft is TFollowToXQVObject) then exit(false);
result := false;//not working: xpathparser.StaticContext.compareDeepAtomic(v, TFollowToXQVObject(ft).v, xpathparser.StaticContext.collation) = 0;
end;
{ TOptionReaderWrapper }
function TOptionReaderWrapper.read(const name: string; var value: IXQValue): boolean;
begin
ignore(name);
ignore(value);
result := false;
end;
function TOptionReaderWrapper.read(const name: string ; var inputformat: TInputFormat): boolean;
var
temp: String = '';
begin
result := read(name, temp);
if result then
case temp of
'auto': inputFormat:=ifAuto;
'xml': inputFormat:=ifXML;
'html': inputFormat:=ifHTML;
'xml-strict': inputFormat:=ifXMLStrict;
'json': inputFormat := ifJSON;
'json-strict': inputFormat := ifJSONStrict;
'text': inputFormat := ifPlainText;
else raise EXidelException.Create('Invalid input-format: '+temp);
end;
end;
function TOptionReaderWrapper.read(const name: string; var value: trilean): boolean;
var temp: boolean = false;
begin
result := read(name, temp);
if not result then value := tUnknown
else if temp then value := tTrue
else value := tfalse;
end;
{ TDataObject }
function TDataObject.rawData: string;
begin
result := frawdata;
end;
function TDataObject.baseUri: string;
begin
result := fbaseurl;
end;
function TDataObject.displayBaseUri: string;
begin
result := fdisplaybaseurl;
end;
function TDataObject.contentType: string;
begin
result := fcontenttype;
end;
function TDataObject.headers: THTTPHeaderList;
begin
result := fheaders;
end;
function TDataObject.recursionLevel: integer;
begin
result := frecursionLevel;
end;
function TDataObject.inputFormat: TInputFormat;
var
enc: TSystemCodePage;
begin
if finputformat = ifAuto then begin
case guessFormat(rawData, baseUri, contentType) of
itfUnknown, itfPlainText: finputformat := ifPlainText;
itfXML, itfXMLPreparsedEntity: finputformat := ifXML;
itfHTML: finputformat := ifHTML;
itfJSON: finputformat := ifJSON;
end;
if (finputformat in [ifJSON,ifJSONStrict]) and (hasOutputEncoding <> oePassRaw) then begin
//convert json to utf-8, because the regex parser does not match non-utf8 (not even with . escape)
//it might be useful to convert other data, but the x/html parser does its own encoding detection
enc := strEncodingFromContentType(contentType);
if enc = CP_NONE then
if isInvalidUTF8Guess(frawData, 32*1024) and not strContains(frawData, #0) then enc := CP_WINDOWS1252;
if (enc <> CP_UTF8) and (enc <> CP_NONE) then frawdata := strConvertToUtf8(frawData, enc);
end;
end;
result := finputFormat;
end;
{ TFollowToProcessedData }
constructor TFollowToProcessedData.create(d: IData);
begin
data := d;
end;
function TFollowToProcessedData.clone: TFollowTo;
begin
result := TFollowToProcessedData.Create(data);
result.inputFormat := inputFormat;
end;
function TFollowToProcessedData.retrieve(parent: TProcessingContext; arecursionLevel: integer): IData;
begin
result := data;
if data <> nil then begin
(result as TDataObject).finputFormat := self.inputFormat;
(result as TDataObject).frecursionLevel := arecursionLevel;
end;
end;
function TFollowToProcessedData.equalTo(ft: TFollowTo): boolean;
begin
result := (ft is TFollowToProcessedData) and (TFollowToProcessedData(ft).data = data);
end;
{ TOptionReaderFromObject }
constructor TOptionReaderFromObject.create(aobj: TXQBoxedMapLike);
begin
obj := aobj;
end;
function TOptionReaderFromObject.read(const name: string; var value: string): boolean;
var
temp: IXQValue;
begin
result := obj.hasProperty(name, temp);
if result then value := temp.toString
end;
function TOptionReaderFromObject.read(const name: string; var value: integer): boolean;
var
temp: IXQValue;
begin
result := obj.hasProperty(name, temp);
if result then value := temp.toInt64
end;
function TOptionReaderFromObject.read(const name: string; var value: boolean): boolean;
var
temp: IXQValue;
begin
result := obj.hasProperty(name, temp);
if result then value := temp.toBoolean
end;
function TOptionReaderFromObject.read(const name: string; var value: Extended): boolean;
var
temp: IXQValue;
begin
result := obj.hasProperty(name, temp);
if result then value := temp.toDouble
end;
function TOptionReaderFromObject.read(const name: string; var value: IXQValue): boolean;
begin
result := obj.hasProperty(name, value);
end;
{ TOptionReaderFromCommandLine }
constructor TOptionReaderFromCommandLine.create(cmdLine: TCommandLineReader);
begin
acmdLine := cmdLine;
end;
function TOptionReaderFromCommandLine.read(const name: string; var value: string): boolean;
begin
value := acmdLine.readString(name);
result := acmdLine.existsProperty(name);
end;
function TOptionReaderFromCommandLine.read(const name: string; var value: integer): boolean;
begin
value := acmdLine.readInt(name);
result := acmdLine.existsProperty(name);
end;
function TOptionReaderFromCommandLine.read(const name: string; var value: boolean): boolean;
begin
value := acmdLine.readFlag(name);
result := acmdLine.existsProperty(name);
end;
function TOptionReaderFromCommandLine.read(const name: string; var value: Extended): boolean;
begin
value := acmdLine.readFloat(name);
result := acmdLine.existsProperty(name);
end;
{ TDownload }
function TDownload.process(data: IData): TFollowToList;
var
realUrl: String;