-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdocument.rb
2718 lines (2308 loc) · 93.7 KB
/
document.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
require 'rdf'
require 'rdf/vocab'
require 'intertwingler/util/clean'
require 'intertwingler/nlp'
require 'intertwingler/vocab/ci'
require 'intertwingler/vocab/qb'
require 'time'
require 'stringio'
require 'nokogiri'
require 'md-noko'
require 'uuid-ncname'
require 'xml-mixup'
require 'mimemagic'
# This is the base class for (X)HTML+RDFa documents. It is a temporary
# situation intended to absorb the dissolution of
# {Intertwingler::Context::Document} and {Intertwingler::Util::Messy}. It will
# eventually get replaced by the much more robust
# {Intertwingler::Representation} paradigm, which, among other things, will
# be able to handle _non_-markup resources like images and such.
class Intertwingler::Document
include XML::Mixup
include Intertwingler::NLP
include Intertwingler::Util::Clean
private
CI = Intertwingler::Vocab::CI
XHV = RDF::Vocab::XHV
R3986 = /^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/
SF = /[^[:alpha:][:digit:]\/\?%@!$&'()*+,:;=._~-]/n
RFC3986 =
/^(?:([^:\/?#]+):)?(?:\/\/([^\/?#]*))?([^?#]+)?(?:\?([^#]*))?(?:#(.*))?$/
SEPS = [['', ?:], ['//', ''], ['', ''], [??, ''], [?#, '']].freeze
# this is a predicate "that does not have children that are not
# scripts"
# predicate says: "node has children other than scripts"
NON_SCRIPTS =
'[text()[normalize-space(.)]|*[not(self::html:script[@src])]]'.freeze
# all blocks minus: details dl fieldset form hr ol ul
BLOCKS = %w[
address article aside blockquote dialog dd div dt fieldset
figcaption figure footer form h1 h2 h3 h4 h5 h6 header hgroup
li main nav p pre section table].freeze
INLINES = %w[a dfn abbr span var kbd samp code q cite data time mark].freeze
# rehydrate boilerplate
RH_BP = '[not(@rel|@rev|@property|@about|@resource|@typeof)]'.freeze
# scraped from https://html.spec.whatwg.org/multipage/indices.html
#
# Array.from(document.getElementById('attributes-1').rows).filter(
# (r) => r.cells[r.cells.length-1].textContent.indexOf('URL') > -1).reduce(
# (a, r) => { let x = r.cells[1].textContent.trim().split(/\s*;\s*/);
# let y = r.cells[0].textContent.trim();
# x.forEach(k => (a[y] ||= []).push(k)); return a }, {})
URL_ATTRS = {
action: %i[form],
cite: %i[blockquote del ins q],
data: %i[object],
formaction: %i[button input],
href: %i[a area link base],
ping: %i[a area],
poster: %i[video],
src: %i[audio embed iframe img input script source track video],
}.freeze
URL_ELEMS = URL_ATTRS.reduce({}) do |hash, pair|
attr, elems = pair
elems.each { |e| (hash[e] ||= []) << attr }
hash
end.freeze
XPATH = {
htmlbase: proc {
x = ['ancestor-or-self::html:html[1]/' \
'html:head[html:base[@href]][1]/html:base[@href][1]/@href']
(x << x.first.gsub('html:', '')).join ?| }.call,
xmlbase: 'ancestor-or-self::*[@xml:base][1]/@xml:base',
lang: 'normalize-space((%s)[last()])' %
%w[lang xml:lang].map do |a|
'ancestor-or-self::*[@%s][1]/@%s' % [a,a]
end.join(?|),
literal: '(ancestor::*[@property][not(@content)]' \
'[not(@resource|@href|@src) or @rel|@rev])[1]',
leaves: 'descendant::html:section[not(descendant::html:section)]' \
'[not(*[not(self::html:script)])]',
headers: './*[1][%s]//text()' %
(1..6).map { |x| "self::html:h#{x}" }.join(?|),
modernize: ([
"//html:div[*[1][#{(1..6).map { |i| 'self::html:h%d' % i }.join ?|}]]"] +
{ div: %i[section figure], blockquote: :note,
table: :figure, img: :figure }.map do |k, v|
(v.is_a?(Array) ? v : [v]).map do |cl|
"//html:#{k}[contains(concat(' ', " \
"normalize-space(@class), ' '), ' #{cl} ')]"
end
end.flatten).join(?|),
# sanitize: './/html:*[%s]' %
# %w[a area img iframe script form object].map do |x|
# 'self::html:%s' % x
# end.join(?|),
sanitize: ".//html:*[%s][not(self::html:base)]" %
(%i[about resource] + URL_ATTRS.keys).map { |x| ?@ + x.to_s }.join(?|),
dehydrate: './/html:a[count(*|text())=1][html:dfn|html:abbr|html:span]',
rehydrate: (
%w[abbr[not(ancestor::html:dfn)]] + (INLINES - %w[a abbr])).map { |e|
".//html:#{e}#{RH_BP}" }.join(?|).freeze,
rh_filter:
'ancestor::html:a|ancestor::*[@property and not(@content)]'.freeze,
htmllinks: (%w[*[not(self::html:base)][@href]/@href
*[@src]/@src object[@data]/@data *[@srcset]/@srcset
form[@action]/@action].map { |e|
'.//html:%s' % e} + %w[//*[@xlink:href]/@xlink:href]).join(?|).freeze,
atomlinks: %w[uri content/@src category/@scheme generator/@uri icon id
link/@href logo].map { |e| './/atom:%s' % e }.join(?|).freeze,
rsslinks: %w[image/text()[1] docs/text()[1] source/@url enclosure/@url
guid/text()[1] comments/text()[1]].map { |e|
'.//%s' % e }.join(?|).freeze,
xlinks: './/*[@xlink:href]/@xlink:href'.freeze,
rdflinks: %w[about resource datatype].map { |e|
'.//*[@rdf:%s]/@rdf:%s' % [e, e] }.join(?|).freeze,
blocks: BLOCKS.map do |b|
pred = BLOCKS.map { |e| "descendant::html:#{e}" }.join ?|
"descendant::html:#{b}#{NON_SCRIPTS}[not(#{pred})]"
end.freeze,
}
XHTMLNS = 'http://www.w3.org/1999/xhtml'.freeze
XPATHNS = {
html: XHTMLNS,
svg: 'http://www.w3.org/2000/svg',
atom: 'http://www.w3.org/2005/Atom',
xlink: 'http://www.w3.org/1999/xlink',
}.freeze
# this grabs a subset of the class methods defined herein and turns
# 'em into instance methods, based on their argument signature
def self.bind_instance_methods
# `false` here gives us only the defined methods, not the inherited ones
methods(false).each do |m|
# obtain the method code itself
proc = method m
# get the argspec
params = proc.parameters
# a lot of methods use the resolver
if params.first == [:req, :resolver]
if params[1] == [:req, :subject]
# a large subset of those follow with the subject
define_method m do |*args, **opts, &block|
proc.call @resolver, @subject, *args, **opts, &block
end
else
# others do something else
define_method m do |*args, **opts, &block|
proc.call @resolver, *args, **opts, &block
end
end
elsif params.first == [:req, :elem]
# the rest operate over xml nodes and stuff
define_method m do |*args, **opts, &block|
proc.call(*args, **opts, &block)
end
end
end
end
public
class Feed < Intertwingler::Document
def generate published: true, backlinks: false
# get related feeds
related = @repo.objects_for(
@subject, RDF::RDFS.seeAlso, only: :uri) - [@subject]
# feed audiences
faudy = @repo.audiences_for @subject
faudn = @repo.audiences_for @subject, invert: true
faudy -= faudn
warn 'feed %s has audiences %s and non-audiences %s' %
[@subject, faudy.inspect, faudn.inspect]
docs = @repo.all_documents external: false, published: published
# now we create a hash keyed by uuid containing the metadata
authors = {}
titles = {}
dates = {}
entries = {}
latest = nil
docs.each do |uu|
# basically make a jsonld-like structure
#rsrc = struct_for uu
# skip unless the entry is indexed
next unless @repo.indexed? uu
# get audiences
audy = @repo.audiences_for uu, proximate: true
audn = @repo.audiences_for uu, proximate: true, invert: true
audy -= audn
warn 'doc %s has audiences %s and non-audiences %s' %
[uu, audy.inspect, audn.inspect]
# we begin by assuming the document is *not* included in the
# feed, and then we try to prove otherwise
skip = true
if audy.empty?
# if both the feed and the document audiences are
# unspecified, then include it, as both are for "everybody"
skip = false if faudy.empty?
elsif faudy.empty?
# if the feed is for everybody but the document is for
# somebody in particular, only include it if its audience is
# in the list of the feed's non-audiences
skip = false unless (audy - faudn).empty?
else
# now we deal with the case where both the feed and the
# document have explicit audiences
# if the document hasn't been explicitly excluded by the
# feed, then include it if it has explicitly been included
skip = false if !(audy - faudn).empty? && !(faudy & audy).empty?
end
next if skip
canon = @resolver.uri_for uu, as: :uri
xml = { '#entry' => [
{ '#link' => nil, rel: :alternate, href: canon, type: 'text/html' },
{ '#id' => uu.to_s }
] }
# get published date first
published = (@repo.objects_for uu,
[RDF::Vocab::DC.issued, RDF::Vocab::DC.created],
datatype: RDF::XSD.dateTime)[0]
# get latest updated date
updated = (@repo.objects_for uu, RDF::Vocab::DC.modified,
datatype: RDF::XSD.dateTime).sort[-1]
updated ||= published || RDF::Literal::DateTime.new(DateTime.now)
updated = Time.parse(updated.to_s).utc
latest = updated if !latest or latest < updated
xml['#entry'].push({ '#updated' => updated.iso8601 })
if published
published = Time.parse(published.to_s).utc
xml['#entry'].push({ '#published' => published.iso8601 })
dates[uu] = [published, updated]
else
dates[uu] = [updated, updated]
end
# get author(s)
al = []
@repo.authors_for(uu).each do |a|
unless authors[a]
n = @repo.label_for a
x = authors[a] = { '#author' => [{ '#name' => n[1].to_s }] }
if hp = @repo.objects_for(
a, RDF::Vocab::FOAF.homepage, only: :resource).sort.first
hp = @resolver.uri_for hp
end
hp ||= @resolver.uri_for a
x['#author'].push({ '#uri' => hp.to_s }) if hp
end
al.push authors[a]
end
xml['#entry'] += al unless al.empty?
# get title (note unshift)
if (t = @repo.label_for uu)
titles[uu] = t[1].to_s
xml['#entry'].unshift({ '#title' => t[1].to_s })
else
titles[uu] = uu.to_s
end
# get abstract
if (d = @repo.label_for uu, desc: true)
xml['#entry'].push({ '#summary' => d[1].to_s })
end
entries[uu] = xml
end
# note we overwrite the entries hash here with a sorted array
entrycmp = -> a, b {
# first we sort by published date
p = dates[a][0] <=> dates[b][0]
# if the published dates are the same, sort by updated date
u = dates[a][1] <=> dates[b][1]
# to break any ties, finally sort by title
p == 0 ? u == 0 ? titles[a] <=> titles[b] : u : p }
entries = entries.values_at(
*entries.keys.sort { |a, b| entrycmp.call(a, b) })
# ugggh god forgot the asterisk and lost an hour
# now we punt out the doc
preamble = [
{ '#id' => @subject.to_s },
{ '#updated' => latest.iso8601 },
{ '#generator' => 'Intertwingler', version: Intertwingler::VERSION,
uri: "https://github.com/doriantaylor/rb-intertwingler" },
{ nil => :link, rel: :self, type: 'application/atom+xml',
href: @resolver.uri_for(@subject) },
{ nil => :link, rel: :alternate, type: 'text/html',
href: @resolver.base },
] + related.map do |r|
{ nil => :link, rel: :related, type: 'application/atom+xml',
href: @resolver.uri_for(r) }
end
if (t = @repo.label_for @subject)
preamble.unshift({ '#title' => t.last.to_s })
end
if (r = @repo.first_literal [@subject, RDF::Vocab::DC.rights, nil])
rh = { '#rights' => r.to_s, type: :text }
rh['xml:lang'] = r.language if r.has_language?
preamble.push rh
end
markup(spec: { '#feed' => preamble + entries,
xmlns: 'http://www.w3.org/2005/Atom' }).document
end
end
class SiteMap < Intertwingler::Document
def generate published: true, backlinks: false
base = resolver.base
urls = {}
@graph.all_documents(external: false, published: published).each do |doc|
next if @graph.rdf_type? doc, RDF::Vocab::FOAF.Image
uri = @resolver.uri_for doc
next unless uri.authority && base && uri.authority == base.authority
mtime = @graph.dates_for(doc).last
nodes = [{ [uri.to_s] => :loc }]
nodes << { [mtime.to_s] => :lastmod } if mtime
urls[uri] = { nodes => :url }
end
urls = urls.sort.map { |_, v| v }
markup(spec: { urls => :urlset,
xmlns: 'http://www.sitemaps.org/schemas/sitemap/0.9' }).document
end
end
class Stats < Intertwingler::Document
private
DSD_SEQ = %i[characters words blocks sections
min low-quartile median high-quartile max mean sd].freeze
TH_SEQ = %w[Document Abstract Created Modified Characters Words Blocks
Sections Min Q1 Median Q3 Max Mean SD].map { |t| { [t] => :th } }
public
def generate published: true, backlinks: false
base = @resolver.uri_for @subject, as: :uri
types = @resolver.abbreviate @repo.asserted_types(@subject)
title = if t = @repo.label_for(@subject)
[t[1].to_s, @resolver.abbreviate(t[0])]
end
cache = {}
@repo.subjects_for(
Intertwingler::Vocab::QB.dataSet, @subject, only: :resource).each do |o|
if d = @repo.objects_for(o, Intertwingler::Vocab::CI.document, only: :resource).first
if !published or @repo.published?(d)
# include a "sort" time that defaults to epoch zero
c = cache[o] ||= {
doc: d, stime: Time.at(0).getgm, struct: @repo.struct_for(o) }
if t = @repo.label_for(d)
c[:title] = t
end
if a = @repo.label_for(d, desc: true)
c[:abstract] = a
end
if ct = @repo.objects_for(d,
RDF::Vocab::DC.created, datatype: RDF::XSD.dateTime).first
c[:stime] = c[:ctime] = ct.object.to_time.getgm
end
if mt = @repo.objects_for(d,
RDF::Vocab::DC.modified, datatype:RDF::XSD.dateTime)
c[:mtime] = mt.map { |m| m.object.to_time.getgm }.sort
c[:stime] = c[:mtime].last unless mt.empty?
end
end
end
end
# sort lambda closure
sl = -> a, b do
x = cache[b][:stime] <=> cache[a][:stime]
return x unless x == 0
x = cache[b][:ctime] <=> cache[a][:ctime]
return x unless x == 0
ta = cache[a][:title] || Array.new(2, cache[a][:uri])
tb = cache[b][:title] || Array.new(2, cache[b][:uri])
ta[1].to_s <=> tb[1].to_s
end
rows = []
cache.keys.sort(&sl).each do |k|
c = cache[k]
href = uri.route_to @resolver.uri_for(c[:doc], as: :uri)
dt = @resolver.abbreviate @repo.asserted_types(c[:doc])
uu = URI(k.to_s).uuid
nc = UUID::NCName.to_ncname uu, version: 1
tp, tt = c[:title] || []
ab = if c[:abstract]
{ [c[:abstract][1].to_s] => :th, about: href,
property: @resolver.abbreviate(c[:abstract].first) }
else
{ [] => :th }
end
td = [{ { { [tt.to_s] => :span,
property: @resolver.abbreviate(tp) } => :a,
rel: 'ci:document', href: href } => :th },
ab,
{ [c[:ctime].iso8601] => :th, property: 'dct:created',
datatype: 'xsd:dateTime', about: href, typeof: dt },
{ c[:mtime].reverse.map { |m| { [m.iso8601] => :span,
property: 'dct:modified', datatype: 'xsd:dateTime' } } => :th,
about: href
},
] + DSD_SEQ.map do |f|
h = []
x = { h => :td }
p = Intertwingler::Vocab::CI[f]
if y = c[:struct][p] and !y.empty?
h << y = y.first
x[:property] = @resolver.abbreviate p
x[:datatype] = @resolver.abbreviate y.datatype if y.datatype?
end
x
end
rows << { td => :tr, id: nc, about: "##{nc}", typeof: 'qb:Observation' }
end
# XXX add something to the vocab so this can be controlled in the data
# xf = config.dig(:stats, :transform) || config[:transform]
XML::Mixup.xhtml_stub(base: base, title: title, attr: {
id: UUID::NCName.to_ncname_64(@subject.to_s),
about: '', typeof: types }, prefix: @resolver.prefixes, content: {
[{ [{ [{ ['About'] => :th, colspan: 4 },
{ ['Counts'] => :th, colspan: 4 },
{ ['Words per Block'] => :th, colspan: 7 }] => :tr },
{ TH_SEQ => :tr } ] => :thead },
{ rows => :tbody, rev: 'qb:dataSet' }] => :table }).document
end
end
# This class is for things like SKOS concept schemes, rosters,
# reading lists, etc.
class Index < Intertwingler::Document
# Generate an alphabetized list with headings for each letter.
#
#
#
# @return [Nokogiri::XML::Document] the generated document.
#
def self.alphabetized_list resolver, subject, fwd: nil, rev: nil,
published: true, preamble: RDF::Vocab::DC.description,
transform: nil, key: nil, cmp: nil, &block
raise ArgumentError,
'We need a block to render the markup! it is not optional!' unless block
repo = resolver.repo
# plump these out
fwd = fwd ? fwd.respond_to?(:to_a) ? fwd.to_a : [fwd] : []
rev = rev ? rev.respond_to?(:to_a) ? rev.to_a : [rev] : []
raise ArgumentError, 'Must have either a fwd or a rev defined' if
fwd.empty? and rev.empty?
# first we get them, then we sort them
frels = {} # forward relations
rrels = {} # reverse relations
alpha = {} # alphabetical map
seen = {} # flat map
# a little metaprogramming to get forward and reverse
[[fwd, [frels, rrels], :objects_for, [subject, fwd]],
[rev, [rrels, frels], :subjects_for, [rev, subject]]
].each do |pa, rel, meth, args|
next if pa.empty?
repo.send meth, *args, only: :resource do |n, pfwd, prev|
# skip if we've already got this (eg with fwd then reverse)
next if seen[n]
# make a dummy so as not to incur calling published? multiple times
seen[n] = {}
# now we set the real struct and get the label
st = seen[n] = repo.struct_for n, inverses: true
# now check if it's published
next if published and
repo.rdf_type?(n, RDF::Vocab::FOAF.Document, struct: st) and
not repo.published?(n)
# now the relations to the subject
rel.map { |r| r[n] ||= Set.new }
rel.first[n] |= pfwd
rel.last[n] |= prev
lab = (repo.label_for(n, struct: st) || [nil, n]).last.value.strip
# find the first letter that isn't an article
lab.gsub!(/\A[[:punct:][:space:]]*(?:An?|The)[[:space:]]+/i, '')
# get the index character which will be unicode, hence these
# festive character classes
char = if match = /\A[[:punct:][:space:]]*
(?:([[:digit:]])|([[:word:]])|([[:graph:]]))
/x.match(lab)
match[2] ? match[2].upcase : ?#
else
?#
end
# add { node => struct } under this heading
(alpha[char] ||= {})[n] = st
end
end
# up until now we didn't need this; also add it to seen
struct = seen[subject] ||= repo.struct_for subject, inverses: true
# duplicate the seen that gets passed into the block otherwise
# what happens is stuff that should show up in the <head> is
# skipped because it's doing double duty as a struct cache as
# well as a manifest of body links
bseen = seen.dup
# obtain the base and prefixes and generate the node spec
base = resolver.uri_for subject, as: :rdf, slugs: true
spec = alpha.sort { |a, b| a.first <=> b.first }.map do |key, structs|
# sort these and run the block
sections = structs.sort do |a, b|
if a.nil? or b.nil?
raise "#{key.inspect} => #{structs.inspect}"
end
al = repo.label_for(a.first, noop: true, struct: a.last).last
bl = repo.label_for(b.first, noop: true, struct: b.last).last
al.value.upcase <=> bl.value.upcase
end.map do |s, st|
# now we call the block
fr = frels[s].to_a if frels[s] and !frels[s].empty?
rr = rrels[s].to_a if rrels[s] and !rrels[s].empty?
# XXX it may be smart to just pass all the structs in
block.call s, fr, rr, st, base, bseen
end.compact
{ ([{[key] => :h2 }] + sections) => :section }
end
# now we get the page metadata
pfx = resolver.prefix_subset(seen).transform_values(&:to_s)
abs = repo.label_for(subject, struct: struct, desc: true)
mn = abs ? { abs.last => :description } : {} # not an element!
meta = head_meta(resolver, subject, struct: struct, meta_names: mn,
vocab: XHV) + twitter_meta(resolver, subject)
links = head_links resolver, subject, struct: struct, vocab: XHV,
ignore: seen.keys, rev: Intertwingler::Vocab::CI.document
types = resolver.abbreviate repo.types_for(subject, struct: struct)
title = if t = repo.label_for(subject, struct: struct)
[t.last.to_s, resolver.abbreviate(t.first)]
end
if abs
para = { [abs.last.to_s] => :p,
property: resolver.abbreviate(abs.first) }
para['xml:lang'] = abs.last.language if abs.last.language?
para[:datatype] = abs.last.datatype if abs.last.datatype?
spec.unshift para
end
XML::Mixup.xhtml_stub(base: base, title: title, transform: transform,
prefix: pfx, vocab: XHV, link: links, meta: meta,
attr: { id: UUID::NCName.to_ncname_64(subject.to_s.dup),
about: '', typeof: types }, content: spec
).document
end
bind_instance_methods
end
# This will generate an (X)HTML+RDFa page containing either a
# SKOS concept scheme or a collection, ordered or otherwise.
#
# XXX later on we should consider conneg for languages
#
class ConceptScheme < Index
CLASSES = [RDF::Vocab::SKOS.ConceptScheme, RDF::Vocab::SKOS.Collection]
def generate published: true, backlinks: false
# stick some logic here to sort out what kind of thing it is
# (concept scheme, collection, ordered collection)
# run this once
rels = {
broader: 'Has Broader',
narrower: 'Has Narrower',
related: 'Has Related' }.map do |k, v|
[@repo.property_set(RDF::Vocab::SKOS[k]), v]
end
skospreds = rels.map(&:first).reduce(Set[]) { |s, a| s | a }.freeze
struct = @repo.struct_for subject
neighbours = { subject => struct }
types = @repo.types_for(subject, struct: struct)
if @repo.type_is?(types, RDF::Vocab::SKOS.OrderedCollection)
# sort
list = if head = @repo.objects_for(
subject, RDF::Vocab::SKOS.memberList, only: :blank).sort.first
RDF::List.new(subject: head, graph: @repo).to_a.map do |s|
next if published and not @repo.published?(s)
neighbours[s] ||= {}
{ [] => :script, type: 'application/xhtml+xml',
src: @resolver.uri_for(s, slugs: true) }
end.compact
end
spec = [{ list => :article, inlist: '',
rel: @resolver.abbreviate(RDF::Vocab::SKOS.memberList) }]
abs = @repo.label_for(subject, struct: struct, desc: true)
mn = abs ? { abs.last => :description } : {} # not an element!
meta = head_meta(subject, struct: struct, meta_names: mn,
vocab: XHV) + twitter_meta(subject)
links = head_links subject, struct: struct, vocab: XHV,
ignore: neighbours.keys
title = if t = @graph.label_for(subject, struct: struct)
[t.last.to_s, @resolver.abbreviate(t.first)]
end
if abs
para = { [abs.last.to_s] => :p,
property: @resolver.abbreviate(abs.first) }
para['xml:lang'] = abs.last.language if abs.last.language?
para[:datatype] = abs.last.datatype if abs.last.datatype?
spec.unshift para
end
pfx = @resolver.prefix_subset neighbours
XML::Mixup.xhtml_stub(base: base, title: title, transform: @transform,
prefix: pfx, vocab: XHV, link: links, meta: meta,
attr: { id: UUID::NCName.to_ncname_64(subject, version: 1),
about: '', typeof: @resolver.abbreviate(types) },
content: spec).document
elsif @repo.type_is?(types, RDF::Vocab::SKOS.Collection)
# make a flat list of just transclusions
alphabetized_list fwd: RDF::Vocab::SKOS.member,
published: published do |s, fp, rp, struct, base, seen|
# just return the sections i guess lol
{ [''] => :script, type: 'application/xhtml+xml',
src: @resolver.uri_for(s, slugs: true),
rel: @resolver.abbreviate(fp),
typeof: @resolver.abbreviate(
@repo.types_for(s, struct: struct)) }
end
elsif @repo.type_is?(types, RDF::Vocab::SKOS.ConceptScheme)
# note i'm not sure about this whole 'seen' business
# WOOF lol
alphabetized_list rev: RDF::Vocab::SKOS.inScheme,
published: published do |s, fp, rp, struct, base, seen|
# may as well bag this while we're at it
neighbours[s] ||= struct
# sequence of elements beginning with the heading
el = begin
lp, lo = @repo.label_for(s, struct: struct)
if lp
[literal_tag(lo, name: :h3, property: lp,
prefixes: @resolver.prefixes)]
else
[{ [s.to_s] => :h3 }]
end
end
# now we do definitions
cmp = @repo.cmp_term
el += @repo.find_in_struct(struct, RDF::Vocab::SKOS.definition,
entail: true, invert: true).sort do |a, b|
cmp.(a.first, b.first)
end.map do |o, ps|
rel = @resolver.abbreviate(ps)
if o.uri?
{ { [''] => :script, type: 'application/xhtml+xml',
src: @resolver.uri_for(o, slugs: true) } => :p, rel: rel }
else
para = { [o.value] => :p, property: rel }
para['xml:lang'] = para[:lang] = o.language if o.language?
para[:datatype] = o.datatype if o.datatype?
para
end.compact
end
# do alternate labels
dl = @repo.find_in_struct(struct, RDF::Vocab::SKOS.altLabel,
entail: true, invert: true).sort do |a, b|
a.first <=> b.first
end.map do |o, ps|
next unless o.literal?
dd = { [o.value] => :dd, property: @resolver.abbreviate(ps) }
dd[:'xml:lang'] = dd[:lang] = o.language if o.language?
dd[:datatype] = o.datatype if o.datatype?
dd
end.compact
dl.unshift({ ['Also known as'] => :dt }) unless dl.empty?
# do relations
dl += rels.map do |pred, dt|
# this will give us a map of neighbours to the predicates
# actually used to relate them
objs = @repo.find_in_struct struct, pred, invert: true
# plump up the structs
objs.keys.each do |k|
# neighbours[k] goes first or it is short circuited
neighbours[k] ||= seen[k] ||= @resolver.struct_for(k,
uuids: true, inverses: true)
end
# only show relations to concepts in this scheme
objs.select! do |k, _|
x = @repo.find_in_struct neighbours[k],
RDF::Vocab::SKOS.inScheme, entail: true, invert: true
x.key? subject
end
unless objs.empty?
lcmp = @repo.cmp_label
[{ [dt] => :dt }] + objs.sort do |a, b|
lcmp.(a.first, b.first)
end.map do |o, ps|
# XXX this is where i would like canonical_uri to
# just "know" to do this (also this will fail if
# this is not a uuid)
# id = UUID::NCName.to_ncname_64(o.value.dup, version: 1)
olp, olo = @repo.label_for(o, struct: neighbours[o])
href = @resolver.uri_for(o)
# href = base.dup
# href.fragment = id
{ link_tag(href, rel: ps, base: base,
typeof: @repo.asserted_types(o, struct: struct),
property: olp, label: olo,
prefixes: @resolver.prefixes ) => :dd }
end
end
end.compact
# do backreferences
op = @repo.query([nil, nil, s]).to_a.select do |stmt|
sj = stmt.subject
if sj.uri? and sj != subject
# XXX there is probably a better way to do this
ref_ok = if neighbours[sj]
np = neighbours[sj].keys.to_set - skospreds -
[RDF::Vocab::SKOS.member,
RDF::Vocab::SKOS.hasTopConcept]
no = neighbours[sj].values_at(*np.to_a).flatten.uniq
!np.empty? and no.include? s
else
true
end
ref_ok and (!published or @repo.published?(sj))
end
end.reduce({}) do |hash, stmt|
sj = stmt.subject
seen[sj] ||= neighbours[sj] ||= @repo.struct_for(sj, inverses: true)
unless skospreds.include? stmt.predicate
(hash[sj] ||= []) << stmt.predicate
end
hash
end
# warn s, op
unless op.empty?
dl << { ['Referenced By'] => :dt }
op.sort do |a, b|
al = (@repo.label_for(a.first,
struct: neighbours[a.first]) || [a.first]).last
bl = (@repo.label_for(b.first,
struct: neighbours[b.first]) || [b.first]).last
al.value.upcase <=> bl.value.upcase
end.each do |sj, ps|
st = neighbours[sj]
href = @resolver.uri_for sj, slugs: true
olp, olo = @repo.label_for(sj, struct: st)
dl << { link_tag(href, rev: ps, base: base,
typeof: @repo.asserted_types(sj, struct: st),
property: olp, label: olo,
prefixes: @resolver.prefixes) => :dd }
end
end
# add see also
sa = @repo.find_in_struct(
struct, RDF::RDFS.seeAlso, invert: true).each do |o, _|
seen[o] ||= neighbours[o] ||= @repo.struct_for(o, inverses: true)
end
unless sa.empty?
dl << { ['See Also'] => :dt }
lcmp = @repo.cmp_label cache: neighbours
sa.keys.sort(&lcmp).each do |o|
href = @resolver.uri_for o, slugs: true
if st = neighbours[o]
olp, olo = @repo.label_for(o, struct: st)
dl << { link_tag(href, rel: sa[o], base: base,
typeof: @repo.types_for(o, struct: st),
property: olp, label: olo,
prefixes: @resolver.prefixes) => :dd }
else
dl << { link_tag(href, rel: ps, base: base) => :dd }
end
end
end
# add to set
el << { dl => :dl } unless dl.empty?
# id = UUID::NCName.to_ncname_64(s.value.dup, version: 1)
resource = @resolver.uri_for(s, slugs: true, as: :uri) || URI(s.to_s)
id = resource.fragment || UUID::NCName.to_ncname_64(s.value.dup, version: 1)
sec = { el => :section, id: id, resource: uri.route_to(resource) }
if typ = @repo.asserted_types(s, struct: struct)
sec[:typeof] = @resolver.abbreviate typ
end
sec[:rel] = @resolver.abbreviate(fp) if fp
sec[:rev] = @resolver.abbreviate(rp) if rp
sec
end
else
raise ArgumentError,
"Subject #{subject} must be some kind of SKOS entity"
end
end
end
class AddressBook < Index
# XXX do we use this mechanism or something else
CLASSES = [RDF::Vocab::SiocTypes.AddressBook]
private
FOAF = RDF::Vocab::FOAF
ORG = RDF::Vocab::ORG
SKOS = RDF::Vocab::SKOS
def org_cmp
end
# we expect to add the result of this to an array
def dl_entry struct, label, predicate: nil, type: nil, reversed: false
struct = repo.find_in_struct struct, predicate, entail: true if predicate
struct = struct.transform_values do |v|
v.select { |w| repo.rdf_type? w, type }
end.reject { |_, v| v.empty? } if type
return [] if struct.empty?
out = [{ [label] => :dt }]
# warn struct.inspect
# deal with multiple entries
inv = repo.invert_struct struct
cache = {}
lcmp = repo.cmp_label nocase: true, cache: cache
inv.keys.sort(&lcmp).each do |k|
preds = resolver.abbreviate inv[k]
out << if k.uri?
rel, rev = nil, nil
reversed ? rev = preds : rel = preds
t = repo.types_for k
u = resolver.uri_for k, slugs: true
lp, lv = repo.label_for k, struct: cache[k]
# warn [lp, lv].inspect
tag = link_tag(u, rel: rel, rev: rev, typeof: t,
property: lp, label: lv)
{ [tag] => :dd }
else
literal_tag k, name: :dd, property: preds
end
end
out
end
def outer_tag subject, rel, rev, struct, base, body,
id: true, resource: false, tag: :section
rel = resolver.coerce_resources rel
rev = resolver.coerce_resources rev
base = resolver.coerce_resource base, as: :uri
uri = resolver.uri_for subject, slugs: true, as: :uri
frag = uri.fragment
# id, rel, resource, typeof
out = { body => tag }
out[:id] = frag if id and frag and !frag.empty?
out[resource ? :resource : :about] = base.route_to uri
out[:rel] = resolver.abbreviate rel if rel
out[:rev] = resolver.abbreviate rev if rev
types = repo.types_for subject, struct: struct
out[:typeof] = resolver.abbreviate(types) unless types.empty?
# punt it
out
end
# if organization, gather up sub-organizations
# separate sub-organizations from true units
# gather up members (distinct from sub-organizations)
# separate members into people and organizations
# separate headOf
#
# we will deal with posts, sites, temporal (memberships, change
# events etc) later
def do_org subject, rel, rev, struct, base, seen, published: false,
bl: false, tag: :section, depth: 0, id: true, resource: false
# zeroth we have the heading
h = depth > 3 ? 3 : depth + 3
lp, lv = repo.label_for subject, struct: struct, noop: true
out = [literal_tag(
lv, name: "h#{h}".to_sym, property: lp, prefixes: resolver.prefixes)]
# first we have a dl with names and website and stuff
# * foaf:name if the heading was not foaf:name
# * skos:altLabel and foaf:nick
# * foaf:homepage
# * org:subOrganizationOf but not org:unitOf if this is a unit
names = []
if lp and repo.property? lp, SKOS.prefLabel
# we'll treat foaf:name as the official name while skos:prefLabel
names += dl_entry struct, 'Official Name', predicate: FOAF.name
end
names += dl_entry struct, 'Also Known As', predicate: SKOS.altLabel
names += dl_entry struct, 'Website', predicate: FOAF.homepage
# only add dl if there's something in it
out << { names => :dl } unless names.empty?
# then we have a description if present
dp, dv = repo.label_for subject, struct: struct, desc: true
out << literal_tag(dv, name: :p, property: dp,
prefixes: resolver.prefixes) if dp
# get a reverse struct with inverses because headOf is only person -> org
rs = repo.struct_for subject, rev: true, inverses: true
inv = repo.invert_struct struct # also the "inverse forward" struct
cmp = repo.cmp_label nocase: true, cache: seen
# then we have a thing for key people (not doing posts yet tho
# so no titles or whatever, just headOf and members
people = dl_entry rs, 'Head', predicate: ORG.headOf, reversed: true
people += dl_entry struct, 'Members',
predicate: ORG.hasMember, type: FOAF.Person
out << { people => :dl } unless people.empty?