-
Notifications
You must be signed in to change notification settings - Fork 11
/
reader.rb
1524 lines (1389 loc) · 65.9 KB
/
reader.rb
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
begin
require 'nokogiri'
rescue LoadError
:rexml
end
require 'rdf/ntriples'
require 'rdf/xsd'
module RDF::RDFa
##
# An RDFa parser in Ruby
#
# This class supports [Nokogiri][] for HTML
# processing, and will automatically select the most performant
# implementation (Nokogiri or LibXML) that is available. If need be, you
# can explicitly override the used implementation by passing in a
# `:library` option to `Reader.new` or `Reader.open`.
#
# [Nokogiri]: https://nokogiri.org/
#
# Based on processing rules described here:
# @see https://www.w3.org/TR/rdfa-syntax/#s_model RDFa 1.0
# @see https://www.w3.org/TR/2012/REC-rdfa-core-20120607/
# @see https://www.w3.org/TR/2012/CR-xhtml-rdfa-20120313/
# @see https://dev.w3.org/html5/rdfa/
#
# @author [Gregg Kellogg](https://greggkellogg.net/)
class Reader < RDF::Reader
format Format
include Expansion
include RDF::Util::Logger
XHTML = "http://www.w3.org/1999/xhtml"
# Content model for @about and @resource. In RDFa 1.0, this was URIorSafeCURIE
SafeCURIEorCURIEorIRI = {
:"rdfa1.0" => [:safe_curie, :uri, :bnode],
:"rdfa1.1" => [:safe_curie, :curie, :uri, :bnode],
}
# Content model for @datatype. In RDFa 1.0, this was CURIE
# Also plural TERMorCURIEorAbsIRIs, content model for @rel, @rev, @property and @typeof
TERMorCURIEorAbsIRI = {
:"rdfa1.0" => [:term, :curie],
:"rdfa1.1" => [:term, :curie, :absuri],
}
# This expression matches an NCName as defined in
# [XML-NAMES](https://www.w3.org/TR/2009/REC-xml-names-20091208/#NT-NCName)
#
# @see https://www.w3.org/TR/2009/REC-xml-names-20091208/#NT-NCName
NC_REGEXP = Regexp.new(
%{^
( [a-zA-Z_]
| \\\\u[0-9a-fA-F]{4}
)
( [0-9a-zA-Z_\.-/]
| \\\\u([0-9a-fA-F]{4})
)*
$},
Regexp::EXTENDED)
# This expression matches an term as defined in
# [RDFA-CORE](https://www.w3.org/TR/2012/REC-rdfa-core-20120607/#s_terms)
#
# For the avoidance of doubt, this definition means a 'term'
# in RDFa is an XML NCName that also permits slash as a non-leading character.
# @see https://www.w3.org/TR/2012/REC-rdfa-core-20120607/#s_terms
TERM_REGEXP = Regexp.new(
%{^
(?!\\\\u0301) # ́ is a non-spacing acute accent.
# It is legal within an XML Name, but not as the first character.
( [a-zA-Z_]
| \\\\u[0-9a-fA-F]{4}
)
( [-0-9a-zA-Z_\.\/]
| \\\\u([0-9a-fA-F]{4})
)*
$},
Regexp::EXTENDED)
# Host language
# @!attribute [r] host_language
# @return [:xml, :xhtml1, :xhtml5, :html4, :html5, :svg]
attr_reader :host_language
# Version
# @!attribute [r] version
# @return [:"rdfa1.0", :"rdfa1.1"]
attr_reader :version
# Repository used for collecting triples.
# @!attribute [r] repository
# @return [RDF::Repository]
attr_reader :repository
# Returns the XML implementation module for this reader instance.
#
# @!attribute [rw] implementation
# @return [Module]
attr_reader :implementation
# The Recursive Baggage
# @private
class EvaluationContext # :nodoc:
##
# The base.
#
# This will usually be the URL of the document being processed,
# but it could be some other URL, set by some other mechanism,
# such as the (X)HTML base element. The important thing is that it establishes
# a URL against which relative paths can be resolved.
#
# @!attribute [rw] base
# @return [RDF::URI]
attr_accessor :base
##
# The parent subject.
#
# The initial value will be the same as the initial value of base,
# but it will usually change during the course of processing.
#
# @!attribute [rw] parent_subject
# @return [RDF::URI]
attr_accessor :parent_subject
##
# The parent object.
#
# In some situations the object of a statement becomes the subject of any nested statements,
# and this property is used to convey this value.
# Note that this value may be a bnode, since in some situations a number of nested statements
# are grouped together on one bnode.
# This means that the bnode must be set in the containing statement and passed down,
# and this property is used to convey this value.
#
# @!attribute [rw] parent_object
# @return [RDF::URI]
attr_accessor :parent_object
##
# A list of current, in-scope URI mappings.
#
# @!attribute [rw] uri_mappings
# @return [Hash{Symbol => String}]
attr_accessor :uri_mappings
##
# A list of current, in-scope Namespaces. This is the subset of uri_mappings
# which are defined using xmlns.
#
# @!attribute [rw] namespaces
# @return [Hash{String => Namespace}]
attr_accessor :namespaces
##
# A list of incomplete triples.
#
# A triple can be incomplete when no object resource
# is provided alongside a predicate that requires a resource (i.e., @rel or @rev).
# The triples can be completed when a resource becomes available,
# which will be when the next subject is specified (part of the process called chaining).
#
# @!attribute [rw] incomplete_triples
# @return [Array<Array<RDF::URI, RDF::Resource>>]
attr_accessor :incomplete_triples
##
# The language. Note that there is no default language.
#
# @!attribute [rw] language
# @return [Symbol]
attr_accessor :language
##
# The term mappings, a list of terms and their associated URIs.
#
# This specification does not define an initial list.
# Host Languages may define an initial list.
# If a Host Language provides an initial list, it should do so via an RDFa Context document.
#
# @!attribute [rw] term_mappings
# @return [Hash{Symbol => RDF::URI}]
attr_accessor :term_mappings
##
# The default vocabulary
#
# A value to use as the prefix URI when a term is used.
# This specification does not define an initial setting for the default vocabulary.
# Host Languages may define an initial setting.
#
# @!attribute [rw] default_vocabulary
# @return [RDF::URI]
attr_accessor :default_vocabulary
##
# lists
#
# A hash associating lists with properties.
# @!attribute [rw] list_mapping
# @return [Hash{RDF:URI: Array<RDF::Resource>}]
attr_accessor :list_mapping
# @param [RDF::URI] base
# @param [Hash] host_defaults
# @option host_defaults [Hash{String => RDF::URI}] :term_mappings Hash of NCName => URI
# @option host_defaults [Hash{String => RDF::URI}] :vocabulary Hash of prefix => URI
def initialize(base, host_defaults)
# Initialize the evaluation context, [5.1]
@base = base
@parent_subject = @base
@parent_object = nil
@namespaces = {}
@incomplete_triples = []
@language = nil
@uri_mappings = host_defaults.fetch(:uri_mappings, {})
@term_mappings = host_defaults.fetch(:term_mappings, {})
@default_vocabulary = host_defaults.fetch(:vocabulary, nil)
end
# Copy this Evaluation Context
#
# @param [EvaluationContext] from
def initialize_copy(from)
# clone the evaluation context correctly
@uri_mappings = from.uri_mappings.clone
@incomplete_triples = from.incomplete_triples.clone
@namespaces = from.namespaces.clone
@list_mapping = from.list_mapping # Don't clone
end
def inspect
v = ['base', 'parent_subject', 'parent_object', 'language', 'default_vocabulary'].map do |a|
"#{a}=#{o = self.send(a); o.respond_to?(:to_ntriples) ? o.to_ntriples : o.inspect}"
end
v << "uri_mappings[#{uri_mappings.keys.length}]"
v << "incomplete_triples[#{incomplete_triples.length}]"
v << "term_mappings[#{term_mappings.keys.length}]"
v << "lists[#{list_mapping.keys.length}]" if list_mapping
v.join(", ")
end
end
##
# RDFa Reader options
# @see https://ruby-rdf.github.io/rdf/RDF/Reader#options-class_method
def self.options
super + [
RDF::CLI::Option.new(
symbol: :vocab_expansion,
datatype: TrueClass,
default: false,
control: :checkbox,
on: ["--vocab-expansion"],
description: "Perform OWL2 expansion on the resulting graph.") {true},
RDF::CLI::Option.new(
symbol: :host_language,
datatype: %w(xml xhtml1 xhtml5 html4 html5 svg),
default: :html5,
control: :select,
on: ["--host-language HOSTLANG", %w(xml xhtml1 xhtml5 html4 html5 svg)],
description: "Host Language. One of xml, xhtml1, xhtml5, html4, or svg") do |arg|
arg.to_sym
end,
RDF::CLI::Option.new(
symbol: :rdfagraph,
datatype: %w(output processor both),
default: :output,
control: :select,
on: ["--rdfagraph RDFAGRAPH", %w(output processor both)],
description: "Used to indicate if either or both of the :output or :processor graphs are output.") {|arg| arg.to_sym},
]
end
##
# Initializes the RDFa reader instance.
#
# @param [IO, File, String] input
# the input stream to read
# @param [Hash{Symbol => Object}] options
# any additional options (see `RDF::Reader#initialize`)
# @option options [Symbol] :library
# One of :nokogiri or :rexml. If nil/unspecified uses :nokogiri if available, :rexml otherwise.
# @option options [Boolean] :vocab_expansion (false)
# whether to perform OWL2 expansion on the resulting graph
# @option options [Boolean] :reference_folding (true)
# whether to perform RDFa property copying on the resulting graph
# @option options [:xml, :xhtml1, :xhtml5, :html4, :html5, :svg] :host_language (:html5)
# Host Language
# @option options [:"rdfa1.0", :"rdfa1.1"] :version (:"rdfa1.1")
# Parser version information
# @option options [Proc] :processor_callback (nil)
# Callback used to provide processor graph triples.
# @option options [Array<Symbol>] :rdfagraph ([:output])
# Used to indicate if either or both of the :output or :processor graphs are output.
# Value is an array containing on or both of :output or :processor.
# @option options [Repository] :vocab_repository (nil)
# Repository to save loaded vocabularies.
# @return [reader]
# @yield [reader] `self`
# @yieldparam [RDF::Reader] reader
# @yieldreturn [void] ignored
# @raise [RDF::ReaderError] if _validate_
def initialize(input = $stdin, **options, &block)
super do
@options = {reference_folding: true}.merge(@options)
@repository = RDF::Repository.new
@options[:rdfagraph] = case @options[:rdfagraph]
when 'all' then [:output, :processor]
when String, Symbol then @options[:rdfagraph].to_s.split(',').map(&:strip).map(&:to_sym)
when Array then @options[:rdfagraph].map {|o| o.to_s.to_sym}
else []
end.select {|o| [:output, :processor].include?(o)}
@options[:rdfagraph] << :output if @options[:rdfagraph].empty?
@library = case options[:library]
when nil
# Use Nokogiri when available, and REXML otherwise:
defined?(::Nokogiri) ? :nokogiri : :rexml
when :nokogiri, :rexml
options[:library]
else
raise ArgumentError.new("expected :rexml or :nokogiri, but got #{options[:library].inspect}")
end
require "rdf/rdfa/reader/#{@library}"
@implementation = case @library
when :nokogiri then Nokogiri
when :rexml then REXML
end
self.extend(@implementation)
detect_host_language_version(input, **options)
add_info(@doc, "version = #{@version}, host_language = #{@host_language}, library = #{@library}, rdfagraph = #{@options[:rdfagraph].inspect}, expand = #{@options[:vocab_expansion]}")
begin
initialize_xml(input, **options)
rescue
add_error(nil, "Malformed document: #{$!.message}")
end
add_error(nil, "Empty document") if root.nil?
add_error(nil, doc_errors.map(&:message).uniq.join("\n")) if !doc_errors.empty?
# Section 4.2 RDFa Host Language Conformance
#
# The Host Language may require the automatic inclusion of one or more Initial Contexts
@host_defaults = {
vocabulary: nil,
uri_mappings: {},
initial_contexts: [],
}
if @version == :"rdfa1.0"
# Add default term mappings
@host_defaults[:term_mappings] = %w(
alternate appendix bookmark cite chapter contents copyright first glossary help icon index
last license meta next p3pv1 prev role section stylesheet subsection start top up
).inject({}) { |hash, term| hash[term] = RDF::URI("http://www.w3.org/1999/xhtml/vocab#") + term; hash }
end
case @host_language
when :xml, :svg
@host_defaults[:initial_contexts] = [XML_RDFA_CONTEXT]
when :xhtml1
@host_defaults[:initial_contexts] = [XML_RDFA_CONTEXT, XHTML_RDFA_CONTEXT]
when :xhtml5, :html4, :html5
@host_defaults[:initial_contexts] = [XML_RDFA_CONTEXT, HTML_RDFA_CONTEXT]
end
block.call(self) if block_given?
end
end
##
# Extracts RDF from script element, or embeded RDF/XML
def extract_script(el, input, type, **options, &block)
add_debug(el, "script element of type #{type}")
begin
# Formats don't exist unless they've been required
case type.to_s
when 'application/csvm+json' then require 'rdf/tabular'
when 'application/ld+json' then require 'json/ld'
when 'application/rdf+xml' then require 'rdf/rdfxml'
when 'text/ntriples' then require 'rdf/ntriples'
when 'text/turtle' then require 'rdf/turtle'
end
rescue LoadError
end
@readers ||= {}
reader = @readers[type.to_s] = RDF::Reader.for(content_type: type.to_s) unless @readers.has_key?(type.to_s)
if reader = @readers[type.to_s]
add_debug(el, "=> reader #{reader.to_sym}")
# Wrap input in a RemoteDocument with appropriate content-type and base
doc = if input.is_a?(String)
RDF::Util::File::RemoteDocument.new(input, content_type: type.to_s, **options)
else
input
end
reader.new(doc, **options).each(&block)
else
add_debug(el, "=> no reader found")
end
end
##
# Iterates the given block for each RDF statement in the input.
#
# Reads to graph and performs expansion if required.
#
# @yield [statement]
# @yieldparam [RDF::Statement] statement
# @return [void]
def each_statement(&block)
if block_given?
unless @processed || @root.nil?
# Add prefix definitions from host defaults
@host_defaults[:uri_mappings].each_pair do |prefix, value|
prefix(prefix, value)
end
# parse
parse_whole_document(@doc, RDF::URI(base_uri))
# Look for Embedded RDF/XML
unless @root.xpath("//rdf:RDF", "rdf" => "http://www.w3.org/1999/02/22-rdf-syntax-ns#").empty?
extract_script(@root, @doc, "application/rdf+xml", **@options.merge(base_uri: base_uri)) do |statement|
@repository << statement
end
end
# Look for Embedded microdata
unless @root.xpath("//@itemscope").empty?
begin
require 'rdf/microdata'
add_debug(@doc, "process microdata")
@repository << RDF::Microdata::Reader.new(@doc, **options)
rescue LoadError
add_debug(@doc, "microdata detected, not processed")
end
end
# Perform property copying
copy_properties(@repository) if @options[:reference_folding]
# Perform vocabulary expansion
expand(@repository) if @options[:vocab_expansion]
@processed = true
end
# Return statements in the default graph for
# statements in the associated named or default graph from the
# processed repository
@repository.each do |statement|
case statement.graph_name
when nil
yield statement if @options[:rdfagraph].include?(:output)
when RDF::RDFA.ProcessorGraph
yield RDF::Statement.new(*statement.to_triple) if @options[:rdfagraph].include?(:processor)
end
end
if validate? && log_statistics[:error]
raise RDF::ReaderError, "Errors found during processing"
end
end
enum_for(:each_statement)
end
##
# Iterates the given block for each RDF triple in the input.
#
# @yield [subject, predicate, object]
# @yieldparam [RDF::Resource] subject
# @yieldparam [RDF::URI] predicate
# @yieldparam [RDF::Value] object
# @return [void]
def each_triple(&block)
if block_given?
each_statement do |statement|
block.call(*statement.to_triple)
end
end
enum_for(:each_triple)
end
private
# Keep track of allocated BNodes
def bnode(value = nil)
@bnode_cache ||= {}
@bnode_cache[value.to_s] ||= RDF::Node.new(value)
end
# Figure out the document path, if it is an Element or Attribute
def node_path(node)
"<#{base_uri}>#{node.respond_to?(:display_path) ? node.display_path : node}"
end
# Add debug event to debug array, if specified
#
# @param [#display_path, #to_s] node XML Node or string for showing context
# @param [String] message
# @yieldreturn [String] appended to message, to allow for lazy-evaulation of message
def add_debug(node, message = "", &block)
add_processor_message(node, message, nil, &block)
end
def add_info(node, message, process_class = RDF::RDFA.Info, &block)
add_processor_message(node, message, process_class, &block)
end
def add_warning(node, message, process_class = RDF::RDFA.Warning)
add_processor_message(node, message, process_class)
end
def add_error(node, message, process_class = RDF::RDFA.Error)
add_processor_message(node, message, process_class)
end
def add_processor_message(node, message, process_class, &block)
case process_class
when RDF::RDFA.Error then log_error(node_path(node), message, &block)
when RDF::RDFA.Warning then log_warn(node_path(node), message, &block)
when RDF::RDFA.Info then log_info(node_path(node), message, &block)
else log_debug(node_path(node), message, &block)
end
process_class ||= RDF::RDFA.Info
if @options[:processor_callback] || @options[:rdfagraph].include?(:processor)
n = RDF::Node.new
processor_statements = [
RDF::Statement.new(n, RDF["type"], process_class, graph_name: RDF::RDFA.ProcessorGraph),
RDF::Statement.new(n, RDF::URI("http://purl.org/dc/terms/description"), message, graph_name: RDF::RDFA.ProcessorGraph),
RDF::Statement.new(n, RDF::URI("http://purl.org/dc/terms/date"), RDF::Literal::Date.new(DateTime.now), graph_name: RDF::RDFA.ProcessorGraph)
]
processor_statements << RDF::Statement.new(n, RDF::RDFA.context, base_uri, graph_name: RDF::RDFA.ProcessorGraph) if base_uri
if node.respond_to?(:path)
nc = RDF::Node.new
processor_statements += [
RDF::Statement.new(n, RDF::RDFA.context, nc, graph_name: RDF::RDFA.ProcessorGraph),
RDF::Statement.new(nc, RDF["type"], RDF::PTR.XPathPointer, graph_name: RDF::RDFA.ProcessorGraph),
RDF::Statement.new(nc, RDF::PTR.expression, node.path, graph_name: RDF::RDFA.ProcessorGraph)
]
end
@repository.insert(*processor_statements)
if cb = @options[:processor_callback]
processor_statements.each {|s| cb.call(s)}
end
end
end
##
# add a statement, object can be literal or URI or bnode
# Yields {RDF::Statement} to the saved callback
#
# @param [#display_path, #to_s] node XML Node or string for showing context
# @param [RDF::Resource] subject the subject of the statement
# @param [RDF::URI] predicate the predicate of the statement
# @param [RDF::Value] object the object of the statement
# @param [RDF::Value] graph_name the graph name of the statement
# @raise [RDF::ReaderError] Checks parameter types and raises if they are incorrect if parsing mode is _validate_.
def add_triple(node, subject, predicate, object, graph_name = nil)
statement = RDF::Statement.new(subject, predicate, object)
add_error(node, "statement #{RDF::NTriples.serialize(statement)} is invalid") unless statement.valid?
if subject && predicate && object # Basic sanity checking
add_info(node, "statement: #{RDF::NTriples.serialize(statement)}")
repository << statement
end
end
# Parsing an RDFa document (this is *not* the recursive method)
def parse_whole_document(doc, base)
base = doc_base(base)
if (base)
# Strip any fragment from base
base = base.to_s.split("#").first
base = uri(base)
add_debug("") {"parse_whole_doc: base='#{base}'"}
end
# initialize the evaluation context with the appropriate base
evaluation_context = EvaluationContext.new(base, @host_defaults)
if @version != :"rdfa1.0"
# Process default vocabularies
load_initial_contexts(@host_defaults[:initial_contexts]) do |which, value|
add_debug(root) { "parse_whole_document, #{which}: #{value.inspect}"}
case which
when :uri_mappings then evaluation_context.uri_mappings.merge!(value)
when :term_mappings then evaluation_context.term_mappings.merge!(value)
when :default_vocabulary then evaluation_context.default_vocabulary = value
end
end
end
traverse(root, evaluation_context)
add_debug("", "parse_whole_doc: traversal complete'")
end
# Parse and process URI mappings, Term mappings and a default vocabulary from @context
#
# Yields each mapping
def load_initial_contexts(initial_contexts)
initial_contexts.
map {|uri| uri(uri).normalize}.
each do |uri|
# Don't try to open ourselves!
if base_uri == uri
add_debug(root) {"load_initial_contexts: skip recursive context #{uri.to_base}"}
next
end
old_logger = @options[:logger]
begin
add_info(root, "load_initial_contexts: load #{uri.to_base}")
@options[:logger] = false
context = Context.find(uri)
# Add URI Mappings to prefixes
context.prefixes.each_pair do |prefix, value|
prefix(prefix, value)
end
yield :uri_mappings, context.prefixes unless context.prefixes.empty?
yield :term_mappings, context.terms unless context.terms.empty?
yield :default_vocabulary, context.vocabulary if context.vocabulary
rescue Exception => e
options[:logger] = old_logger
add_error(root, e.message)
raise # In case we're not in strict mode, we need to be sure processing stops
ensure
@options[:logger] = old_logger
end
end
end
# Extract the prefix mappings from an element
def extract_mappings(element, uri_mappings, namespaces)
# look for xmlns
# (note, this may be dependent on @host_language)
# Regardless of how the mapping is declared, the value to be mapped must be converted to lower case,
# and the URI is not processed in any way; in particular if it is a relative path it is
# not resolved against the current base.
ns_defs = {}
element.namespaces.each do |prefix, href|
prefix = nil if prefix == "xmlns"
add_debug("extract_mappings") { "ns: #{prefix}: #{href}"}
ns_defs[prefix] = href
end
# HTML parsing doesn't create namespace_definitions
if ns_defs.empty?
ns_defs = {}
element.attributes.each do |attr, href|
next unless attr =~ /^xmlns(?:\:(.+))?/
prefix = $1
add_debug("extract_mappings") { "ns(attr): #{prefix}: #{href}"}
ns_defs[prefix] = href
end
end
ns_defs.each do |prefix, href|
# A Conforming RDFa Processor must ignore any definition of a mapping for the '_' prefix.
next if prefix == "_"
href = uri(base_uri, href).to_s
# Downcase prefix for RDFa 1.1
pfx_lc = (@version == :"rdfa1.0" || prefix.nil?) ? prefix : prefix.downcase
if prefix
if uri_mappings.fetch(pfx_lc.to_sym, href) != href
add_warning(element, "Redefining prefix #{pfx_lc}: from <#{uri_mappings[pfx_lc]}> to <#{href}>", RDF::RDFA.PrefixRedefinition)
end
uri_mappings[pfx_lc.to_sym] = href
namespaces[pfx_lc] ||= href
prefix(pfx_lc, href)
add_info(element, "extract_mappings: #{prefix} => <#{href}>")
else
add_info(element, "extract_mappings: nil => <#{href}>")
namespaces[""] ||= href
end
end
# Set mappings from @prefix
# prefix is a whitespace separated list of prefix-name URI pairs of the form
# NCName ':' ' '+ xs:anyURI
mappings = element.attribute("prefix").to_s.strip.split(/\s+/)
while mappings.length > 0 do
prefix, uri = mappings.shift.downcase, mappings.shift
#puts "uri_mappings prefix #{prefix} #{uri.to_base}"
next unless prefix.match(/:$/)
prefix.chop!
unless prefix.empty? || prefix.match(NC_REGEXP)
add_error(element, "extract_mappings: Prefix #{prefix.inspect} does not match NCName production")
next
end
# A Conforming RDFa Processor must ignore any definition of a mapping for the '_' prefix.
next if prefix == "_"
uri = uri(base_uri, uri).to_s
pfx_index = prefix.to_s.empty? ? nil : prefix.to_s.to_sym
if uri_mappings.fetch(pfx_index, uri) != uri
add_warning(element, "Redefining prefix #{prefix}: from <#{uri_mappings[pfx_index]}> to <#{uri}>", RDF::RDFA.PrefixRedefinition)
end
uri_mappings[pfx_index] = uri
prefix(prefix, uri)
add_info(element, "extract_mappings: prefix #{prefix} => <#{uri}>")
end unless @version == :"rdfa1.0"
end
# The recursive helper function
def traverse(element, evaluation_context)
if element.nil?
add_error(element, "Can't parse nil element")
return nil
end
add_debug(element) { "ec: #{evaluation_context.inspect}" }
# local variables [7.5 Step 1]
recurse = true
skip = false
new_subject = nil
typed_resource = nil
current_object_resource = nil
uri_mappings = evaluation_context.uri_mappings.clone
namespaces = evaluation_context.namespaces.clone
incomplete_triples = []
language = evaluation_context.language
term_mappings = evaluation_context.term_mappings.clone
default_vocabulary = evaluation_context.default_vocabulary
list_mapping = evaluation_context.list_mapping
xml_base = element.base
base = xml_base.to_s if xml_base && ![:xhtml1, :html4, :html5].include?(@host_language)
add_debug(element) {"base: #{base.inspect}"} if base
base ||= evaluation_context.base
# Pull out the attributes needed for the skip test.
attrs = {}
%w(
about
content
datatype
datetime
href
id
inlist
property
rel
resource
rev
role
src
type
typeof
value
vocab
).each do |a|
attrs[a.to_sym] = element.attributes[a].to_s.strip if element.attributes[a]
end
add_debug(element) {"attrs " + attrs.inspect} unless attrs.empty?
# If @property and @rel/@rev are on the same elements, the non-CURIE and non-URI @rel/@rev values are ignored. If, after this, the value of @rel/@rev becomes empty, then the then the processor must act as if the attribute is not present.
if attrs.has_key?(:property) && @version == :"rdfa1.1" && (@host_language == :html5 || @host_language == :xhtml5 || @host_language == :html4)
[:rel, :rev].each do |attr|
next unless attrs.has_key?(attr)
add_debug(element) {"Remove non-CURIE/non-IRI @#{attr} values from #{attrs[attr].inspect}"}
attrs[attr] = attrs[attr].
split(/\s+/).
select {|a| a.index(':')}.
join(" ")
add_debug(element) {" => #{attrs[attr].inspect}"}
attrs.delete(attr) if attrs[attr].empty?
end
end
# Default vocabulary [7.5 Step 2]
# Next the current element is examined for any change to the default vocabulary via @vocab.
# If @vocab is present and contains a value, its value updates the local default vocabulary.
# If the value is empty, then the local default vocabulary must be reset to the Host Language defined default.
if attrs[:vocab]
default_vocabulary = if attrs[:vocab].empty?
# Set default_vocabulary to host language default
add_debug(element) {
"[Step 3] reset default_vocaulary to #{@host_defaults.fetch(:vocabulary, nil).inspect}"
}
@host_defaults.fetch(:vocabulary, nil)
else
# Generate a triple indicating that the vocabulary is used
add_triple(element, base, RDF::RDFA.usesVocabulary, uri(attrs[:vocab]))
uri(attrs[:vocab])
end
add_debug(element) {
"[Step 2] default_vocaulary: #{default_vocabulary.inspect}"
}
end
# Local term mappings [7.5 Step 3]
# Next, the current element is then examined for URI mapping s and these are added to the local list of URI mappings.
# Note that a URI mapping will simply overwrite any current mapping in the list that has the same name
extract_mappings(element, uri_mappings, namespaces)
# Language information [7.5 Step 4]
language = element.language || language
language = nil if language.to_s.empty?
add_debug(element) {"HTML5 [3.2.3.3] lang: #{language.inspect}"} if language
# Embedded scripts
if element.name == 'script'
text = element.inner_html.sub(%r(\A\s*\<!\[CDATA\[)m, '').sub(%r(\]\]>\s*\Z)m, '')
extract_script(element, text, attrs[:type], **@options.merge(base_uri: base)) do |statement|
@repository << statement
end
end
# From HTML5, if the property attribute and the rel and/or rev attribute exists on the same element, the non-CURIE and non-URI rel and rev values are ignored. If, after this, the value of rel and/or rev becomes empty, then the processor must act as if the respective attribute is not present.
if [:html5, :xhtml5].include?(@host_language) && attrs[:property] && (attrs[:rel] || attrs[:rev])
old_rel, old_rev = attrs[:rel], attrs[:rev]
if old_rel
attrs[:rel] = (attrs[:rel]).split(/\s+/m).select {|r| !r.index(':').nil?}.join(" ")
attrs.delete(:rel) if attrs[:rel].empty?
add_debug(element) {"HTML5: @rel was #{old_rel}, now #{attrs[:rel]}"}
end
if old_rev
attrs[:rev] = (attrs[:rev]).split(/\s+/m).select {|r| !r.index(':').nil?}.join(" ")
attrs.delete(:rev) if attrs[:rev].empty?
add_debug(element) {"HTML5: @rev was #{old_rev}, now #{attrs[:rev]}"}
end
end
# rels and revs
rels = process_uris(element, attrs[:rel], evaluation_context, base,
uri_mappings: uri_mappings,
term_mappings: term_mappings,
vocab: default_vocabulary,
restrictions: TERMorCURIEorAbsIRI.fetch(@version, []))
revs = process_uris(element, attrs[:rev], evaluation_context, base,
uri_mappings: uri_mappings,
term_mappings: term_mappings,
vocab: default_vocabulary,
restrictions: TERMorCURIEorAbsIRI.fetch(@version, []))
add_debug(element) do
"rels: #{rels.join(" ")}, revs: #{revs.join(" ")}"
end unless (rels + revs).empty?
if !(attrs[:rel] || attrs[:rev])
# Establishing a new subject if no rel/rev [7.5 Step 5]
if @version == :"rdfa1.0"
new_subject = if attrs[:about]
process_uri(element, attrs[:about], evaluation_context, base,
uri_mappings: uri_mappings,
restrictions: SafeCURIEorCURIEorIRI.fetch(@version, []))
elsif attrs[:resource]
process_uri(element, attrs[:resource], evaluation_context, base,
uri_mappings: uri_mappings,
restrictions: SafeCURIEorCURIEorIRI.fetch(@version, []))
elsif attrs[:href] || attrs[:src]
process_uri(element, (attrs[:href] || attrs[:src]), evaluation_context, base, restrictions: [:uri])
end
# If no URI is provided by a resource attribute, then the first match from the following rules
# will apply:
new_subject ||= if [:xhtml1, :xhtml5, :html4, :html5].include?(@host_language) && element.name =~ /^(head|body)$/
# From XHTML+RDFa 1.1:
# if no URI is provided, then first check to see if the element is the head or body element.
# If it is, then act as if the new subject is set to the parent object.
uri(base)
elsif element == root && base
# if the element is the root element of the document, then act as if there is an empty @about present,
# and process it according to the rule for @about, above;
uri(base)
elsif attrs[:typeof]
RDF::Node.new
else
# otherwise, if parent object is present, new subject is set to the value of parent object.
skip = true unless attrs[:property]
evaluation_context.parent_object
end
# if the @typeof attribute is present, set typed resource to new subject
typed_resource = new_subject if attrs[:typeof]
else # rdfa1.1
# If the current element contains no @rel or @rev attribute, then the next step is to establish a value for new subject.
# This step has two possible alternatives.
# 1. If the current element contains the @property attribute, but does not contain the @content or the @datatype attributes, then
if attrs[:property] && !(attrs[:content] || attrs[:datatype])
# new subject is set to the resource obtained from the first match from the following rule:
new_subject ||= if attrs[:about]
# by using the resource from @about, if present, obtained according to the section on CURIE and IRI Processing;
process_uri(element, attrs[:about], evaluation_context, base,
uri_mappings: uri_mappings,
restrictions: SafeCURIEorCURIEorIRI.fetch(@version, []))
elsif [:xhtml1, :xhtml5, :html4, :html5].include?(@host_language) && element.name =~ /^(head|body)$/
# From XHTML+RDFa 1.1:
# if no URI is provided, then first check to see if the element is the head or body element. If it is, then act as if the new subject is set to the parent object.
evaluation_context.parent_object
elsif element == root && base
# otherwise, if the element is the root element of the document, then act as if there is an empty @about present, and process it according to the rule for @about, above;
uri(base)
end
# if the @typeof attribute is present, set typed resource to new subject
typed_resource = new_subject if attrs[:typeof]
# otherwise, if parent object is present, new subject is set to the value of parent object.
new_subject ||= evaluation_context.parent_object
# If @typeof is present then typed resource is set to the resource obtained from the first match from the following rules:
# by using the resource from @about, if present, obtained according to the section on CURIE and IRI Processing; (done above)
# otherwise, if the element is the root element of the document, then act as if there is an empty @about present and process it according to the previous rule; (done above)
if attrs[:typeof] && typed_resource.nil?
# otherwise,
typed_resource ||= if attrs[:resource]
# by using the resource from @resource, if present, obtained according to the section on CURIE and IRI Processing;
process_uri(element, attrs[:resource], evaluation_context, base,
uri_mappings: uri_mappings,
restrictions: SafeCURIEorCURIEorIRI.fetch(@version, []))
elsif attrs[:href] || attrs[:src]
# otherwise, by using the IRI from @href, if present, obtained according to the section on CURIE and IRI Processing;
# otherwise, by using the IRI from @src, if present, obtained according to the section on CURIE and IRI Processing;
process_uri(element, (attrs[:href] || attrs[:src]), evaluation_context, base,
restrictions: [:uri])
else
# otherwise, the value of typed resource is set to a newly created bnode.
RDF::Node.new
end
# The value of the current object resource is set to the value of typed resource.
current_object_resource = typed_resource
end
else
# otherwise (ie, the @content or @datatype)
new_subject =
process_uri(element, (attrs[:about] || attrs[:resource]),
evaluation_context, base,
uri_mappings: uri_mappings,
restrictions: SafeCURIEorCURIEorIRI.fetch(@version, [])) if attrs[:about] ||attrs[:resource]
new_subject ||=
process_uri(element, (attrs[:href] || attrs[:src]), evaluation_context, base,
restrictions: [:uri]) if attrs[:href] || attrs[:src]
# If no URI is provided by a resource attribute, then the first match from the following rules
# will apply:
new_subject ||= if [:xhtml1, :xhtml5, :html4, :html5].include?(@host_language) && element.name =~ /^(head|body)$/
# From XHTML+RDFa 1.1:
# if no URI is provided, then first check to see if the element is the head or body element.
# If it is, then act as if the new subject is set to the parent object.
evaluation_context.parent_object
elsif element == root
# if the element is the root element of the document, then act as if there is an empty @about present,
# and process it according to the rule for @about, above;
uri(base)
elsif attrs[:typeof]
RDF::Node.new
else
# otherwise, if parent object is present, new subject is set to the value of parent object.
# Additionally, if @property is not present then the skip element flag is set to 'true'.
skip = true unless attrs[:property]
evaluation_context.parent_object
end
# If @typeof is present then typed resource is set to the resource obtained from the first match from the following rules:
typed_resource = new_subject if attrs[:typeof]
end
end
add_debug(element) {
"[Step 5] new_subject: #{new_subject.to_ntriples rescue 'nil'}, " +
"typed_resource: #{typed_resource.to_ntriples rescue 'nil'}, " +
"current_object_resource: #{current_object_resource.to_ntriples rescue 'nil'}, " +
"skip = #{skip}"
}
else
# [7.5 Step 6]
# If the current element does contain a @rel or @rev attribute, then the next step is to
# establish both a value for new subject and a value for current object resource:
new_subject = process_uri(element, attrs[:about], evaluation_context, base,
uri_mappings: uri_mappings,
restrictions: SafeCURIEorCURIEorIRI.fetch(@version, []))
new_subject ||= process_uri(element, attrs[:src], evaluation_context, base,
uri_mappings: uri_mappings,
restrictions: [:uri]) if @version == :"rdfa1.0"
# if the @typeof attribute is present, set typed resource to new subject
typed_resource = new_subject if attrs[:typeof]