/usr/share/perl5/XRD/Parser.pm is in libxrd-parser-perl 0.201-3.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 | package XRD::Parser;
use 5.010;
use strict;
use Carp 0;
use Digest::SHA 0 qw(sha1_hex);
use Encode 0 qw(encode_utf8);
use HTTP::Link::Parser 0.102;
use LWP::UserAgent 0;
use Object::AUTHORITY 0;
use RDF::Trine 0.135;
use Scalar::Util 0 qw(blessed);
use URI::Escape 0;
use URI::URL 0;
use XML::LibXML 1.70 qw(:all);
use constant NS_HOSTMETA => 'http://host-meta.net/ns/1.0';
use constant NS_HOSTMETX => 'http://host-meta.net/xrd/1.0';
use constant NS_XML => XML::LibXML::XML_XML_NS;
use constant NS_XRD => 'http://docs.oasis-open.org/ns/xri/xrd-1.0';
use constant URI_DCTERMS => 'http://purl.org/dc/terms/';
use constant URI_HOST => 'http://ontologi.es/xrd#host:';
use constant URI_RDF => 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
use constant URI_RDFS => 'http://www.w3.org/2000/01/rdf-schema#';
use constant URI_SUBLINK => 'http://ontologi.es/xrd#sublink:';
use constant URI_TYPES => 'http://www.iana.org/assignments/media-types/';
use constant URI_XRD => 'http://ontologi.es/xrd#';
use constant URI_XSD => 'http://www.w3.org/2001/XMLSchema#';
use constant SCHEME_TMPL => 'x-xrd+template+for:';
BEGIN {
$XRD::Parser::AUTHORITY = 'cpan:TOBYINK';
$XRD::Parser::VERSION = '0.201';
}
sub new
{
my ($class, $content, $baseuri, $options, $store)= @_;
# Rationalise $options
# ====================
# If $options is undefined, then use the default configuration
if (!ref $options)
{ $options = {}; }
# Rationalise $baseuri
# ====================
croak "Need a valid base URI.\n"
unless $baseuri =~ /^[a-z][a-z0-9\+\-\.]*:/i;
# Rationalise $content and set $domtree
# =====================================
croak "Need to provide XML content\n"
unless defined $content;
my $domtree;
if (blessed($content) && $content->isa('XML::LibXML::Document'))
{
($domtree, $content) = ($content, $content->toString);
}
else
{
my $xml_parser = XML::LibXML->new;
$domtree = $xml_parser->parse_string($content);
}
# Rationalise $store
# ==================
$store = RDF::Trine::Store::DBI->temporary_store
unless defined $store;
my $self = bless {
'content' => $content,
'baseuri' => $baseuri,
'options' => $options,
'DOM' => $domtree,
'RESULTS' => RDF::Trine::Model->new($store),
}, $class;
return $self;
}
sub new_from_url
{
my ($class, $url, $options, $store)= @_;
if (!ref $options)
{ $options = {}; }
my $ua = LWP::UserAgent->new;
$ua->agent(sprintf('%s/%s (%s) ', __PACKAGE__, __PACKAGE__->VERSION, __PACKAGE__->AUTHORITY));
$ua->default_header("Accept" => "application/xrd+xml, application/xml;q=0.1, text/xml;q=0.1");
my $response;
my $timeout = $options->{timeout} // 60;
eval {
local $SIG{ALRM} = sub { die "Request timed out\n"; };
alarm $timeout;
$response = $ua->get($url);
if ($response->code == 406)
{
$response = $ua->get($url, Accept=>'application/xrd+xml, application/x-httpd-php');
}
alarm 0;
};
croak $@ if $@;
croak "HTTP response not successful\n"
unless defined $response && $response->is_success;
croak "Non-XRD HTTP response\n"
unless $response->content_type =~ m`^(text/xml)|(application/(xrd\+xml|xml))$`
|| ($options->{'loose_mime'} && $response->content_type =~ m`^(text/plain)|(text/html)|(application/octet-stream)$`);
return $class->new(
$response->decoded_content,
$response->base.'',
$options,
$store,
);
}
*new_from_uri = \&new_from_url;
sub hostmeta
{
my $class = shift;
my $host = shift;
my $rv;
my ($https, $http) = hostmeta_location($host);
return unless $https;
eval { $rv = $class->new_from_url($https, {timeout=>10, loose_mime=>1,default_subject=>host_uri($host)}); };
return $rv if $rv;
eval { $rv = $class->new_from_url($http, {timeout=>15, loose_mime=>1,default_subject=>host_uri($host)}); } ;
return $rv if $rv;
return;
}
sub uri
{
my $this = shift;
my $param = shift // '';
my $opts = shift // {};
if ((ref $opts) =~ /^XML::LibXML/)
{
my $x = {'element' => $opts};
$opts = $x;
}
if ($param =~ /^([a-z][a-z0-9\+\.\-]*)\:/i)
{
# seems to be an absolute URI, so can safely return "as is".
return $param;
}
elsif ($opts->{'require-absolute'})
{
return undef;
}
my $base = $this->{baseuri};
if ($this->{'options'}->{'xml_base'})
{
$base = $opts->{'xml_base'} // $this->{baseuri};
}
my $url = url $param, $base;
my $rv = $url->abs->as_string;
# This is needed to pass test case 0114.
while ($rv =~ m!^(http://.*)(\.\./|\.)+(\.\.|\.)?$!i)
{
$rv = $1;
}
return $rv;
}
sub dom
{
my $this = shift;
return $this->{DOM};
}
sub graph
{
my $this = shift;
$this->consume;
return $this->{RESULTS};
}
sub graphs
{
my $this = shift;
$this->consume;
return { $this->{'baseuri'} => $this->{RESULTS} };
}
sub set_callbacks
# Set callback functions for handling RDF triples.
{
my $this = shift;
if ('HASH' eq ref $_[0])
{
$this->{'sub'} = $_[0];
$this->{'sub'}->{'pretriple_resource'} = \&_print0
if lc $this->{'sub'}->{'pretriple_resource'} eq 'print';
$this->{'sub'}->{'pretriple_literal'} = \&_print1
if lc $this->{'sub'}->{'pretriple_literal'} eq 'print';
}
elsif (defined $_[0])
{
croak("What kind of callback hashref was that??\n");
}
else
{
$this->{'sub'} = undef;
}
return $this;
}
sub _print0
# Prints a Turtle triple.
{
my $this = shift;
my $element = shift;
my $subject = shift;
my $pred = shift;
my $object = shift;
my $graph = shift;
if ($graph)
{
print "# GRAPH $graph\n";
}
if ($element)
{
printf("# Triple on element %s.\n", $element->nodePath);
}
else
{
printf("# Triple.\n");
}
printf("%s %s %s .\n",
($subject =~ /^_:/ ? $subject : "<$subject>"),
"<$pred>",
($object =~ /^_:/ ? $object : "<$object>"));
return undef;
}
sub _print1
# Prints a Turtle triple.
{
my $this = shift;
my $element = shift;
my $subject = shift;
my $pred = shift;
my $object = shift;
my $dt = shift;
my $lang = shift;
my $graph = shift;
# Clumsy, but probably works.
$object =~ s/\\/\\\\/g;
$object =~ s/\n/\\n/g;
$object =~ s/\r/\\r/g;
$object =~ s/\t/\\t/g;
$object =~ s/\"/\\\"/g;
if ($graph)
{
print "# GRAPH $graph\n";
}
if ($element)
{
printf("# Triple on element %s.\n", $element->nodePath);
}
else
{
printf("# Triple.\n");
}
no warnings;
printf("%s %s %s%s%s .\n",
($subject =~ /^_:/ ? $subject : "<$subject>"),
"<$pred>",
"\"$object\"",
(length $dt ? "^^<$dt>" : ''),
((length $lang && !length $dt) ? "\@$lang" : '')
);
use warnings;
return undef;
}
sub consume
{
my $this = shift;
return $this if $this->{'consumed'};
my @xrds = $this->{'DOM'}->getElementsByTagNameNS(NS_XRD, 'XRD')->get_nodelist;
my $first = 1;
my $only = (scalar @xrds == 1) ? 1 : 0;
foreach my $XRD (@xrds)
{
$this->_consume_XRD($XRD, $first, $only);
$first = 0
if $first;
}
$this->{'consumed'}++;
return $this;
}
sub _consume_XRD
{
my $this = shift;
my $xrd = shift;
my $first = shift // 0;
my $only = shift // 0;
my $description_uri;
if ($xrd->hasAttributeNS(NS_XML, 'id'))
{
$description_uri = $this->uri('#'.$xrd->getAttributeNS(NS_XML, 'id'));
}
elsif ($only)
{
$description_uri = $this->uri;
}
else
{
$description_uri = $this->bnode;
}
my $subject_node = $xrd->getChildrenByTagNameNS(NS_XRD, 'Subject')->shift;
my $subject;
my @subjects;
$subject = $this->uri(
$this->stringify($subject_node),
{'require-absolute'=>1})
if $subject_node;
push @subjects, $subject
if defined $subject;
NAMESPACE: foreach my $hostmeta_ns (@{[NS_HOSTMETA, NS_HOSTMETX]})
{
my $host_uri;
ELEMENT: foreach my $host_node ($xrd->getChildrenByTagNameNS($hostmeta_ns, 'Host')->get_nodelist)
{
$host_uri = host_uri($this->stringify($host_node));
$subject = $host_uri
unless defined $subject;
push @subjects, $host_uri;
}
last NAMESPACE if $host_uri;
}
unless (@subjects)
{
if ($first && defined $this->{'options'}->{'default_subject'})
{
$subject = $this->{'options'}->{'default_subject'};
push @subjects, $subject;
}
}
unless (@subjects)
{
$subject = $this->bnode($xrd);
push @subjects, $subject;
}
$this->rdf_triple($xrd, $description_uri, URI_XRD.'subject', $subject);
foreach my $alias ( $xrd->getChildrenByTagNameNS(NS_XRD, 'Alias')->get_nodelist )
{
my $alias_uri = $this->uri($this->stringify($alias),{'require-absolute'=>1});
$this->rdf_triple($alias, $subject, URI_XRD.'alias', $alias_uri);
}
my $expires_node = $xrd->getChildrenByTagNameNS(NS_XRD, 'Expires')->shift;
my $expires = $this->stringify($expires_node) if $expires_node;
if (length $expires)
{
$this->rdf_triple_literal($expires_node,
$description_uri, URI_XRD.'expires', $expires, URI_XSD.'dateTime');
}
foreach my $p ($xrd->getChildrenByTagNameNS(NS_XRD, 'Property')->get_nodelist)
{
$this->_consume_Property($p, \@subjects);
}
foreach my $l ($xrd->getChildrenByTagNameNS(NS_XRD, 'Link')->get_nodelist)
{
$this->_consume_Link($l, \@subjects);
}
}
sub _consume_Property
{
my $this = shift;
my $p = shift;
my $S = shift;
my $property_uri = $this->uri(
$p->getAttribute('type'), {'require-absolute'=>1});
return unless $property_uri;
my $value = $this->stringify($p);
foreach my $subject_uri (@$S)
{
$this->rdf_triple_literal(
$p,
$subject_uri,
$property_uri,
$value);
}
}
sub _consume_Link
{
my $this = shift;
my $l = shift;
my $S = shift;
my $property_uri = HTTP::Link::Parser::relationship_uri(
$l->getAttribute('rel'));
return unless $property_uri;
my @value;
my $value_type;
my ($p1,$p2);
if ($l->hasAttribute('href'))
{
push @value, $this->uri($l->getAttribute('href'));
$value_type = 'href';
($p1,$p2) = ('', $property_uri);
}
elsif ($l->hasAttribute('template'))
{
push @value, $l->getAttribute('template');
push @value, URI_XRD . 'URITemplate';
$value_type = 'template';
($p1,$p2) = (SCHEME_TMPL, $property_uri);
$property_uri = template_uri($property_uri);
}
else
{
return;
}
foreach my $subject_uri (@$S)
{
if ($value_type eq 'href')
{
$this->rdf_triple(
$l,
$subject_uri,
$property_uri,
@value);
}
elsif ($value_type eq 'template')
{
$this->rdf_triple_literal(
$l,
$subject_uri,
$property_uri,
@value);
}
}
if ($value_type eq 'href')
{
my $type = $l->getAttribute('type');
if (defined $type)
{
$this->rdf_triple_literal($l, @value, URI_XRD.'type', $type);
}
foreach my $title ($l->getChildrenByTagName('Title')->get_nodelist)
{
my $lang = undef;
if ($title->hasAttributeNS(NS_XML, 'lang'))
{
$lang = $title->getAttributeNS(NS_XML, 'lang');
$lang = undef unless valid_lang($lang);
}
$this->rdf_triple_literal(
$title,
@value,
URI_XRD.'title',
$this->stringify($title),
undef,
$lang);
}
}
foreach my $subject_uri (@$S)
{
my @link_properties = $l->getChildrenByTagNameNS(NS_XRD, 'Property')->get_nodelist;
if (@link_properties)
{
if ($this->{'options'}->{'link_prop'} & 1)
{
my $reified_statement = $this->bnode($l);
$this->rdf_triple($l, $reified_statement, URI_RDF.'type', URI_RDF.'Statement');
$this->rdf_triple($l, $reified_statement, URI_RDF.'subject', $subject_uri);
$this->rdf_triple($l, $reified_statement, URI_RDF.'predicate', $property_uri);
if ($value_type eq 'href')
{
$this->rdf_triple($l, $reified_statement, URI_RDF.'object', @value);
}
else
{
$this->rdf_triple_literal($l, $reified_statement, URI_RDF.'object', @value);
}
foreach my $lp (@link_properties)
{
$this->_consume_Property($lp, [$reified_statement]);
}
}
if ($this->{'options'}->{'link_prop'} & 2)
{
my $subPropUri = $p1 . URI_SUBLINK . uri_escape($p2);
my @modifiers;
foreach my $lp (@link_properties)
{
my $k = $this->uri($lp->getAttribute('type'), {'require-absolute'=>1});
my $v = $this->stringify($lp);
push @modifiers, sprintf('%s=%s', uri_escape($k), uri_escape($v))
if length $k;
}
my $supermodifier = join '&', sort @modifiers;
$subPropUri .= '/' . sha1_hex($supermodifier);
if ($value_type eq 'href')
{
$this->rdf_triple($l, $subject_uri, $subPropUri, @value);
}
else
{
$this->rdf_triple_literal($l, $subject_uri, $subPropUri, @value);
}
$this->rdf_triple($l, $subPropUri, URI_RDF.'type', URI_RDF.'Property');
$this->rdf_triple($l, $subPropUri, URI_RDFS.'subPropertyOf', $property_uri);
foreach my $lp (@link_properties)
{
$this->_consume_Property($lp, [$subPropUri]);
}
}
}
}
}
sub rdf_triple
# Function only used internally.
{
my $this = shift;
my $suppress_triple = 0;
$suppress_triple = $this->{'sub'}->{'pretriple_resource'}($this, @_)
if defined $this->{'sub'}->{'pretriple_resource'};
return if $suppress_triple;
my $element = shift; # A reference to the XML::LibXML element being parsed
my $subject = shift; # Subject URI or bnode
my $predicate = shift; # Predicate URI
my $object = shift; # Resource URI or bnode
my $graph = shift; # Graph URI or bnode (if named graphs feature is enabled)
# First make sure the object node type is ok.
my $to;
if ($object =~ m/^_:(.*)/)
{
$to = RDF::Trine::Node::Blank->new($1);
}
else
{
$to = RDF::Trine::Node::Resource->new($object);
}
# Run the common function
return $this->rdf_triple_common($element, $subject, $predicate, $to, $graph);
}
sub rdf_triple_literal
# Function only used internally.
{
my $this = shift;
my $suppress_triple = 0;
$suppress_triple = $this->{'sub'}->{'pretriple_literal'}($this, @_)
if defined $this->{'sub'}->{'pretriple_literal'};
return if $suppress_triple;
my $element = shift; # A reference to the XML::LibXML element being parsed
my $subject = shift; # Subject URI or bnode
my $predicate = shift; # Predicate URI
my $object = shift; # Resource Literal
my $datatype = shift; # Datatype URI (possibly undef or '')
my $language = shift; # Language (possibly undef or '')
my $graph = shift; # Graph URI or bnode (if named graphs feature is enabled)
# Now we know there's a literal
my $to;
# Work around bad Unicode handling in RDF::Trine.
$object = encode_utf8($object);
if (defined $datatype)
{
if ($datatype eq 'http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral')
{
if ($this->{'options'}->{'use_rtnlx'})
{
eval
{
require RDF::Trine::Node::Literal::XML;
$to = RDF::Trine::Node::Literal::XML->new($element->childNodes);
};
}
if ( $@ || !defined $to)
{
my $orig = $RDF::Trine::Node::Literal::USE_XMLLITERALS;
$RDF::Trine::Node::Literal::USE_XMLLITERALS = 0;
$to = RDF::Trine::Node::Literal->new($object, undef, $datatype);
$RDF::Trine::Node::Literal::USE_XMLLITERALS = $orig;
}
}
else
{
$to = RDF::Trine::Node::Literal->new($object, undef, $datatype);
}
}
else
{
$to = RDF::Trine::Node::Literal->new($object, $language, undef);
}
# Run the common function
$this->rdf_triple_common($element, $subject, $predicate, $to, $graph);
}
sub rdf_triple_common
# Function only used internally.
{
my $this = shift; # A reference to the RDF::RDFa::Parser object
my $element = shift; # A reference to the XML::LibXML element being parsed
my $subject = shift; # Subject URI or bnode
my $predicate = shift; # Predicate URI
my $to = shift; # RDF::Trine::Node Resource URI or bnode
my $graph = shift; # Graph URI or bnode (if named graphs feature is enabled)
# First, make sure subject and predicates are the right kind of nodes
my $tp = RDF::Trine::Node::Resource->new($predicate);
my $ts;
if ($subject =~ m/^_:(.*)/)
{
$ts = RDF::Trine::Node::Blank->new($1);
}
else
{
$ts = RDF::Trine::Node::Resource->new($subject);
}
my $statement;
# If we are configured for it, and graph name can be found, add it.
if (ref($this->{'options'}->{'named_graphs'}) && ($graph))
{
$this->{Graphs}->{$graph}++;
my $tg;
if ($graph =~ m/^_:(.*)/)
{
$tg = RDF::Trine::Node::Blank->new($1);
}
else
{
$tg = RDF::Trine::Node::Resource->new($graph);
}
$statement = RDF::Trine::Statement::Quad->new($ts, $tp, $to, $tg);
}
else
{
$statement = RDF::Trine::Statement->new($ts, $tp, $to);
}
my $suppress_triple = 0;
$suppress_triple = $this->{'sub'}->{'ontriple'}($this, $element, $statement)
if ($this->{'sub'}->{'ontriple'});
return if $suppress_triple;
$this->{RESULTS}->add_statement($statement);
}
sub stringify
# Function only used internally.
{
my $this = shift;
my $dom = shift;
if ($dom->nodeType == XML_TEXT_NODE)
{
return $dom->getData;
}
elsif ($dom->nodeType == XML_ELEMENT_NODE)
{
my $rv = '';
foreach my $kid ($dom->childNodes)
{ $rv .= $this->stringify($kid); }
return $rv;
}
return '';
}
sub xmlify
# Function only used internally.
{
my $this = shift;
my $dom = shift;
my $lang = shift;
my $rv;
foreach my $kid ($dom->childNodes)
{
my $fakelang = 0;
if (($kid->nodeType == XML_ELEMENT_NODE) && defined $lang)
{
unless ($kid->hasAttributeNS(NS_XML, 'lang'))
{
$kid->setAttributeNS(NS_XML, 'lang', $lang);
$fakelang++;
}
}
$rv .= $kid->toStringEC14N(1);
if ($fakelang)
{
$kid->removeAttributeNS(NS_XML, 'lang');
}
}
return $rv;
}
sub bnode
# Function only used internally.
{
my $this = shift;
my $element = shift;
return sprintf('http://thing-described-by.org/?%s#%s',
$this->uri,
$element->getAttributeNS(NS_XML, 'id'))
if ($this->{options}->{tdb_service} && $element && length $element->getAttributeNS(NS_XML, 'id'));
$this->{bnode_prefix} //= do {
my $uuid = Data::UUID->new->create_str;
$uuid =~ s/[^A-Za-z0-9]//g;
$uuid;
};
return sprintf('_:x%sx%03d', $this->{bnode_prefix}, $this->{bnodes}++);
}
sub valid_lang
{
my $value_to_test = shift;
return 1 if (defined $value_to_test) && ($value_to_test eq '');
return 0 unless defined $value_to_test;
# Regex for recognizing RFC 4646 well-formed tags
# http://www.rfc-editor.org/rfc/rfc4646.txt
# http://tools.ietf.org/html/draft-ietf-ltru-4646bis-21
# The structure requires no forward references, so it reverses the order.
# It uses Java/Perl syntax instead of the old ABNF
# The uppercase comments are fragments copied from RFC 4646
# Note: the tool requires that any real "=" or "#" or ";" in the regex be escaped.
my $alpha = '[a-z]'; # ALPHA
my $digit = '[0-9]'; # DIGIT
my $alphanum = '[a-z0-9]'; # ALPHA / DIGIT
my $x = 'x'; # private use singleton
my $singleton = '[a-wyz]'; # other singleton
my $s = '[_-]'; # separator -- lenient parsers will use [_-] -- strict will use [-]
# Now do the components. The structure is slightly different to allow for capturing the right components.
# The notation (?:....) is a non-capturing version of (...): so the "?:" can be deleted if someone doesn't care about capturing.
my $language = '([a-z]{2,8}) | ([a-z]{2,3} $s [a-z]{3})';
# ABNF (2*3ALPHA) / 4ALPHA / 5*8ALPHA --- note: because of how | works in regex, don't use $alpha{2,3} | $alpha{4,8}
# We don't have to have the general case of extlang, because there can be only one extlang (except for zh-min-nan).
# Note: extlang invalid in Unicode language tags
my $script = '[a-z]{4}' ; # 4ALPHA
my $region = '(?: [a-z]{2}|[0-9]{3})' ; # 2ALPHA / 3DIGIT
my $variant = '(?: [a-z0-9]{5,8} | [0-9] [a-z0-9]{3} )' ; # 5*8alphanum / (DIGIT 3alphanum)
my $extension = '(?: [a-wyz] (?: [_-] [a-z0-9]{2,8} )+ )' ; # singleton 1*("-" (2*8alphanum))
my $privateUse = '(?: x (?: [_-] [a-z0-9]{1,8} )+ )' ; # "x" 1*("-" (1*8alphanum))
# Define certain grandfathered codes, since otherwise the regex is pretty useless.
# Since these are limited, this is safe even later changes to the registry --
# the only oddity is that it might change the type of the tag, and thus
# the results from the capturing groups.
# http://www.iana.org/assignments/language-subtag-registry
# Note that these have to be compared case insensitively, requiring (?i) below.
my $grandfathered = '(?:
(en [_-] GB [_-] oed)
| (i [_-] (?: ami | bnn | default | enochian | hak | klingon | lux | mingo | navajo | pwn | tao | tay | tsu ))
| (no [_-] (?: bok | nyn ))
| (sgn [_-] (?: BE [_-] (?: fr | nl) | CH [_-] de ))
| (zh [_-] min [_-] nan)
)';
# old: | zh $s (?: cmn (?: $s Hans | $s Hant )? | gan | min (?: $s nan)? | wuu | yue );
# For well-formedness, we don't need the ones that would otherwise pass.
# For validity, they need to be checked.
# $grandfatheredWellFormed = (?:
# art $s lojban
# | cel $s gaulish
# | zh $s (?: guoyu | hakka | xiang )
# );
# Unicode locales: but we are shifting to a compatible form
# $keyvalue = (?: $alphanum+ \= $alphanum+);
# $keywords = ($keyvalue (?: \; $keyvalue)*);
# We separate items that we want to capture as a single group
my $variantList = $variant . '(?:' . $s . $variant . ')*' ; # special for multiples
my $extensionList = $extension . '(?:' . $s . $extension . ')*' ; # special for multiples
my $langtag = "
($language)
($s ( $script ) )?
($s ( $region ) )?
($s ( $variantList ) )?
($s ( $extensionList ) )?
($s ( $privateUse ) )?
";
# Here is the final breakdown, with capturing groups for each of these components
# The variants, extensions, grandfathered, and private-use may have interior '-'
my $r = ($value_to_test =~
/^(
($langtag)
| ($privateUse)
| ($grandfathered)
)$/xi);
return $r;
}
sub host_uri
{
my $uri = shift;
if ($uri =~ /:/)
{
my $tmpuri = URI->new($uri);
if ($tmpuri->can('host'))
{
return URI_HOST . $tmpuri->host;
}
elsif($tmpuri->can('authority') && $tmpuri->authority =~ /\@/)
{
(undef, my $host) = split /\@/, $tmpuri->authority;
return URI_HOST . $host;
}
elsif($tmpuri->can('opaque') && $tmpuri->opaque =~ /\@/)
{
(undef, my $host) = split /\@/, $tmpuri->opaque;
return URI_HOST . $host;
}
}
else
{
return URI_HOST . $uri;
}
return undef;
}
sub template_uri
{
my $uri = shift;
return SCHEME_TMPL . $uri;
}
sub hostmeta_location
{
my $host = shift;
if ($host =~ /:/)
{
my $u = url $host;
if ($u->can('host'))
{
$host = $u->host;
}
elsif ($u->can('authority') && $u->authority =~ /\@/)
{
(undef, $host) = split /\@/, $u->authority;
}
elsif ($u->can('opaque') && $u->opaque =~ /\@/)
{
(undef, $host) = split /\@/, $u->opaque;
}
}
if (wantarray)
{
return ("https://$host/.well-known/host-meta", "http://$host/.well-known/host-meta");
}
else
{
return "http://$host/.well-known/host-meta";
}
}
1;
__END__
=head1 NAME
XRD::Parser - parse XRD and host-meta files into RDF::Trine models
=head1 SYNOPSIS
use RDF::Query;
use XRD::Parser;
my $parser = XRD::Parser->new(undef, "http://example.com/foo.xrd");
my $results = RDF::Query->new(
"SELECT * WHERE {?who <http://spec.example.net/auth/1.0> ?auth.}")
->execute($parser->graph);
while (my $result = $results->next)
{
print $result->{'auth'}->uri . "\n";
}
or maybe:
my $data = XRD::Parser->hostmeta('gmail.com')
->graph
->as_hashref;
=head1 DESCRIPTION
While XRD has a rather different history, it turns out it can mostly
be thought of as a serialisation format for a limited subset of
RDF.
This package ignores the order of <Link> elements, as RDF is a graph
format with no concept of statements coming in an "order". The XRD spec
says that grokking the order of <Link> elements is only a SHOULD. That
said, if you're concerned about the order of <Link> elements, the
callback routines allowed by this package may be of use.
This package aims to be roughly compatible with RDF::RDFa::Parser's
interface.
=head2 Constructors
=over 4
=item C<< $p = XRD::Parser->new($content, $uri, [\%options], [$store]) >>
This method creates a new XRD::Parser object and returns it.
The $content variable may contain an XML string, or a XML::LibXML::Document.
If a string, the document is parsed using XML::LibXML::Parser, which may throw an
exception. XRD::Parser does not catch the exception.
$uri the base URI of the content; it is used to resolve any relative URIs found
in the XRD document.
Options [default in brackets]:
=over 8
=item * B<default_subject> - If no <Subject> element. [undef]
=item * B<link_prop> - How to handle <Property> in <Link>?
0=skip, 1=reify, 2=subproperty, 3=both. [0]
=item * B<loose_mime> - Accept text/plain, text/html and
application/octet-stream media types. [0]
=item * B<tdb_service> - Use thing-described-by.org when possible. [0]
=back
$storage is an RDF::Trine::Storage object. If undef, then a new
temporary store is created.
=item C<< $p = XRD::Parser->new_from_url($url, [\%options], [$storage]) >>
$url is a URL to fetch and parse.
This function can also be called as C<new_from_uri>. Same thing.
=item C<< $p = XRD::Parser->hostmeta($uri) >>
This method creates a new XRD::Parser object and returns it.
The parameter may be a URI (from which the hostname will be extracted) or
just a bare host name (e.g. "example.com"). The resource
"/.well-known/host-meta" will then be fetched from that host using an
appropriate HTTP Accept header, and the parser object returned.
=back
=head2 Public Methods
=over 4
=item C<< $p->uri($uri) >>
Returns the base URI of the document being parsed. This will usually be the
same as the base URI provided to the constructor.
Optionally it may be passed a parameter - an absolute or relative URI - in
which case it returns the same URI which it was passed as a parameter, but
as an absolute URI, resolved relative to the document's base URI.
This seems like two unrelated functions, but if you consider the consequence
of passing a relative URI consisting of a zero-length string, it in fact makes
sense.
=item C<< $p->dom >>
Returns the parsed XML::LibXML::Document.
=item C<< $p->graph >>
This method will return an RDF::Trine::Model object with all
statements of the full graph.
This method will automatically call C<consume> first, if it has not
already been called.
=item $p->set_callbacks(\%callbacks)
Set callback functions for the parser to call on certain events. These are only necessary if
you want to do something especially unusual.
$p->set_callbacks({
'pretriple_resource' => sub { ... } ,
'pretriple_literal' => sub { ... } ,
'ontriple' => undef ,
});
Either of the two pretriple callbacks can be set to the string 'print' instead of a coderef.
This enables built-in callbacks for printing Turtle to STDOUT.
For details of the callback functions, see the section CALLBACKS. C<set_callbacks> must
be used I<before> C<consume>. C<set_callbacks> itself returns a reference to the parser
object itself.
I<NOTE:> the behaviour of this function was changed in version 0.05.
=item C<< $p->consume >>
This method processes the input DOM and sends the resulting triples to
the callback functions (if any).
It called again, does nothing.
Returns the parser object itself.
=back
=head2 Utility Functions
=over 4
=item C<< $host_uri = XRD::Parser::host_uri($uri) >>
Returns a URI representing the host. These crop up often in graphs gleaned
from host-meta files.
$uri can be an absolute URI like 'http://example.net/foo#bar' or a host
name like 'example.com'.
=item C<< $uri = XRD::Parser::template_uri($relationship_uri) >>
Returns a URI representing not a normal relationship, but the
relationship between a host and a template URI literal.
=item C<< $hostmeta_uri = XRD::Parser::hostmeta_location($host) >>
The parameter may be a URI (from which the hostname will be extracted) or
just a bare host name (e.g. "example.com"). The location for a host-meta file
relevant to the host of that URI will be calculated.
If called in list context, returns an 'https' URI and an 'http' URI as a list.
=back
=head1 CALLBACKS
Several callback functions are provided. These may be set using the C<set_callbacks> function,
which taskes a hashref of keys pointing to coderefs. The keys are named for the event to fire the
callback on.
=head2 pretriple_resource
This is called when a triple has been found, but before preparing the triple for
adding to the model. It is only called for triples with a non-literal object value.
The parameters passed to the callback function are:
=over 4
=item * A reference to the C<XRD::Parser> object
=item * A reference to the C<XML::LibXML::Element> being parsed
=item * Subject URI or bnode (string)
=item * Predicate URI (string)
=item * Object URI or bnode (string)
=back
The callback should return 1 to tell the parser to skip this triple (not add it to
the graph); return 0 otherwise.
=head2 pretriple_literal
This is the equivalent of pretriple_resource, but is only called for triples with a
literal object value.
The parameters passed to the callback function are:
=over 4
=item * A reference to the C<XRD::Parser> object
=item * A reference to the C<XML::LibXML::Element> being parsed
=item * Subject URI or bnode (string)
=item * Predicate URI (string)
=item * Object literal (string)
=item * Datatype URI (string or undef)
=item * Language (string or undef)
=back
The callback should return 1 to tell the parser to skip this triple (not add it to
the graph); return 0 otherwise.
=head2 ontriple
This is called once a triple is ready to be added to the graph. (After the pretriple
callbacks.) The parameters passed to the callback function are:
=over 4
=item * A reference to the C<XRD::Parser> object
=item * A reference to the C<XML::LibXML::Element> being parsed
=item * An RDF::Trine::Statement object.
=back
The callback should return 1 to tell the parser to skip this triple (not add it to
the graph); return 0 otherwise. The callback may modify the RDF::Trine::Statement
object.
=head1 WHY RDF?
It abstracts away the structure of the XRD file, exposing just the meaning
of its contents. Two XRD files with the same meaning should end up producing
more or less the same RDF data, even if they differ significantly at the
syntactic level.
If you care about the syntax of an XRD file, then use L<XML::LibXML>.
=head1 SEE ALSO
L<RDF::Trine>, L<RDF::Query>, L<RDF::RDFa::Parser>.
L<http://www.perlrdf.org/>.
=head1 AUTHOR
Toby Inkster, E<lt>tobyink@cpan.orgE<gt>
=head1 COPYRIGHT AND LICENCE
Copyright (C) 2009-2012 by Toby Inkster
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.
=head1 DISCLAIMER OF WARRANTIES
THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
=cut
|