XDI.pm

filter: Statementstmt 83.3% 10 / 12 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 4 / 4 Podpod n/a totaltotal 87.5% 14 / 16 CC 1 SCAR 0.7
CC
1
Cov
83%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
↑ Summary XDI/Message.pm »
1 package XDI;
2  
3 our $VERSION = '0.05';
4  
5 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 2 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 0 ▶use Log::Log4perl qw(get_logger :levels);
Subroutine BEGIN: called CC=1 SCAR=2.6
10 use JSON::XS;
11 use Data::Dumper;
12 use Data::UUID;
13 use Storable qw(dclone);
14 use Clone qw(clone);
15  
16 use XDI::Connection;
17  
18 require Exporter;
19 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
20  
21  
22 @ISA = qw(Exporter);
23 @EXPORT = qw(
24 pick_xdi_tuple
25 tuples
26 get_literal
27 get_equivalent
28 get_property
29 get_context
30 );
31 %EXPORT_TAGS = ( ); # eg: TAG => [ qw!name1 name2! ],
32  
33 # your exported package globals go here,
34 # as well as any optionally exported functions
35 #@EXPORT_OK = qw($Var1 %Hashit &func3);
36 #use vars qw($Var1 %Hashit);
37  
38 @EXPORT_OK = qw(&s_debug);
39 use vars qw();
40  
41 # non-exported package globals go here
42 #use vars qw(@more $stuff);
43 use vars qw();
44  
45 # file-private lexicals go here
46 my %fields = (
47 from_graph => undef,
48 from => undef,
49 );
50  
51 our $AUTOLOAD;
52 our $USE_LOCAL_MESSAGE = 1;
53  
54  
55 sub new {
56 my $class = shift;
57 my $self = {%fields,};
58 bless($self,$class);
59 my ($var_hash) = @_;
60 if (defined $var_hash ) {
61 if (ref $var_hash eq "HASH"){
62 foreach my $varkey (keys %{$var_hash}) {
63 if (exists $self->{$varkey}) {
64 $self->{$varkey} = $var_hash->{$varkey};
65 }
66 }
67 } elsif (ref $var_hash eq "") {
68 #TODO: resolve iname into iname/inumber
69 $self->{'from'} = $var_hash;
70 $self->{'from_graph'} = $var_hash;
71 } else {
72 croak "Initialization failed: parameters not passed as hash reference or iname string";
73 }
74 }
75 return $self;
76 }
77  
78  
79 sub AUTOLOAD {
80 my $self = shift;
81 my $type = ref($self)
82 or croak "($AUTOLOAD): $self is not an object";
83 my $name = $AUTOLOAD;
84 $name =~ s/.*://;
85 unless ( exists $self->{$name} ) {
86 carp "$name not permitted in class $type";
87 return;
88 }
89  
90 if (@_) {
91 my $obj = shift;
92 if ( ref $obj ne "" ) {
93 return $self->{$name} = dclone $obj;
94 }
95 else {
96 return $self->{$name} = $obj;
97 }
98  
99 }
100 else {
101 return $self->{$name};
102 }
103 }
104  
105 sub connect {
106 my $self = shift;
107 my $connector = XDI::Connection->new($self,@_);
108 return $connector;
109 }
110  
111  
112 sub tuples {
113 my ($graph,$match) = @_;
114 my @matches = ();
115 foreach my $key (sort keys %{$graph}) {
116 my ($subject,$predicate,$value);
117 if ($key =~ m/^(.+)\/(.+)$/) {
118 $subject = $1;
119 $predicate = $2;
120 if (scalar(@{$graph->{$key}}) == 1) {
121  
122 $value = $graph->{$key}->[0];
123 } else {
124 $value = $graph->{$key};
125 }
126  
127 if (defined $match->[0]) {
128 if (ref $match->[0] eq "Regexp") {
129 next unless ($subject =~ m/$match->[0]/);
130 } elsif ($subject ne $match->[0]) {
131 next;
132 }
133 }
134
135  
136 if (defined $match->[1]) {
137 if (ref $match->[1] eq "Regexp") {
138 next unless ($predicate =~ m/$match->[1]/);
139 } elsif ($predicate ne $match->[1]) {
140 next;
141 }
142 }
143  
144 if (defined $match->[2]) {
145 if (ref $match->[2] eq "Regexp") {
146 next unless ($value =~ m/$match->[2]/);
147 } elsif ($value ne $match->[2]) {
148 next;
149 }
150 }
151 push(@matches, [$subject,$predicate,$value]);
152 }
153 }
154 return \@matches;
155 }
156  
157 sub pick_xdi_tuple {
158 my ($graph,$match) = @_;
159 my $logger = get_logger();# $logger->debug("Match: ", sub {Dumper($match)});
160 foreach my $key (keys %{$graph}) {
161 my ($subject,$predicate,$value);
162 if ($key =~ m/^(.+)\/(.+)$/) {
163 $subject = $1;
164 $predicate = $2;
165 if (scalar(@{$graph->{$key}}) == 1) {
166  
167 $value = $graph->{$key}->[0];
168 } else {
169 $value = $graph->{$key};
170 }
171
172 my $ret = 1;
173 if (defined $match->[0] && $match->[0] ne $subject) {
174 $ret = 0;
175 }
176 if ($ret && defined $match->[1] && $match->[1] ne $predicate) {
177 $ret = 0
178 }
179 if ($ret && defined $match->[2] && $match->[2] ne $value) {
180 $ret = 0;
181 }
182 if ($ret) {
183 return [$subject,$predicate,$value];
184 }
185 }
186 }
187 return undef;
188
189 }
190  
191 sub get_literal {
192 my ($graph,$keys) = @_;
193 my $logger= get_logger();
194 my @results = ();
195 if (ref $keys eq "ARRAY") {
196 foreach my $key (@$keys) {
197 my $values = tuples($graph,[$key,'!',undef]);
198 if (defined $values) {
199 foreach my $element (@{$values}) {
200 push(@results,$element->[2]);
201 }
202 }
203
204 }
205 } elsif (ref $keys eq '') {
206 my $values = tuples($graph,[$keys,'!',undef]);
207 if (defined $values) {
208 foreach my $element (@{$values}) {
209 push(@results,$element->[2]);
210 }
211 }
212 }
213 if (scalar(@results) == 1) {
214 return $results[0];
215 } elsif (scalar(@results) > 1) {
216 return \@results;
217 }
218 return undef;
219 }
220  
221 sub get_equivalent {
222 my ($graph,$key) = @_;
223 my @results = ();
224 my $values = tuples($graph,[$key,'$is',undef]);
225 if (defined $values) {
226 foreach my $element (@{$values}) {
227 push(@results,$element->[2]);
228 }
229 return \@results;
230 }
231 return undef;
232 }
233  
234 sub get_property {
235 my ($graph,$key) = @_;
236 my @results = ();
237 my $values = tuples($graph,[$key,'()',undef]);
238 if (defined $values) {
239 foreach my $element (@{$values}) {
240 foreach my $m (@{$element->[2]}){
241 push(@results,$m);
242 }
243 }
244 return \@results;
245 }
246 return undef;
247 }
248  
249 sub get_context {
250 my ($graph,$key) = @_;
251 my @results = ();
252 my $values = tuples($graph,[$key,'$is()',undef]);
253 if (defined $values) {
254 foreach my $element (@{$values}) {
255 foreach my $cl (@{$element->[2]}) {
256 push(@results,$cl);
257 }
258 }
259 return \@results;
260 }
261 return undef;
262 }
263  
264  
265 # Hopefully this will get more sophisticated
266 sub is_inumber {
267 my ($xdi) = @_;
268 return $xdi =~ m/!/;
269 }
270  
271  
272  
273 sub s_debug {
274 my $parent = (caller(0))[0];
275 my $sub = (caller(1))[3];
276 return ($parent,$sub);
277 }
278  
279 sub _decode {
280 my ($string) = @_;
281 my $logger = get_logger();
282 my $struct;
283 eval {
284 $struct = JSON::XS::->new->pretty(1)->decode($string);
285 };
286 if ($@ && not defined $struct) {
287 carp("Not a valid JSON string");
288 carp($@);
289 return undef;
290 } else {
291 return $struct;
292 }
293 }
294  
295  
296 sub DESTROY { }
297  
298 END { } # module clean-up code here (global destructor)
299  
300  
301  
302 1; # End of XDI
303  
304 =head1 NAME
305  
306 XDI - Messaging client for XDI servers
307  
308 =head1 VERSION
309  
310 Version 0.01
311  
312 =cut
313  
314 =head1 SYNOPSIS
315
316 use XDI;
317
318 my $xdi = new XDI;
319
320 ..
321
322 my $iname = '=tester';
323 my $xdi = XDI->new($iname);
324
325 ..
326
327 my $hash = {
328 'from' => '=tester',
329 'from_graph' => '@xdiserver'
330 };
331
332 my $xdi = XDI->new($hash);
333
334 =head1 EXPORTS
335  
336 pick_xdi_tuple
337  
338 =head1 XDI
339  
340 XDI is an open standard semantic graph model, data sharing format, and protocol.
341  
342 Details on XDI can be found at L<https://wiki.oasis-open.org/xdi/FrontPage>
343  
344 XDI graphs are addressed via inames/inumbers which conform to the generic URI syntax
345 as defined in IETF RFC 3986. inames resolve to inumbers. inames can be re-assigned
346 while inumbers are permanent identifiers
347  
348 =head2 inames/inumbers
349  
350 =markus # individual context
351 =!91F2.8153.F600.AE24
352
353 @xdi # institutional context
354 @!3D12.8C35.6FB3.E89C
355  
356 An experimental service to provide XDI iname/inumber resolution is L<http://xri2xdi.net/index.html>
357  
358 CRUD permissions to an XDI database are defined by link contracts. Link contracts define a
359 permission ($get,$add,$mod,$del) for a graph node and who has that permission
360  
361 =head1 DESCRIPTION
362  
363 The XDI perl module provides a client for communicating with XDI servers.
364  
365 =head2 Notation and Conventions
366  
367 $xdi Root object defining identity of querier
368 $c Connection object defining graph target and permissions
369 $msg Message object for XDI messages
370 $hash Reference to a hash of key/attribute values
371
372 =head2 Usage Outline
373  
374 All XDI communications are between two graph entities, these are defined by inames/inumbers
375 Identity verification and authority are still being developed under the XDI specification
376 so this module allows the user to self-assert
377  
378 use XDI;
379
380 $xdi = XDI->new('=tester');
381
382 This constructor assumes that the user making the query I<from> is the same as the graph
383 from which the query is being made I<from_graph>. If you were implementing an XDI service
384 that mediated queries on behalf of a user, it would be appropriate to set the I<from_graph>
385 to the identity of the service
386  
387 $xdi = XDI->new({from => '=tester', from_graph => '@kynetx' });
388
389 To specify the graph to which you would like to query, you create a L<XDI::Connection>
390  
391 $c = $xdi->connect();
392
393 This is the primary method for creating a Connection object so that it can access the fields
394 of the XDI object.
395  
396 You can pass any XDI::Connection initialization parameters to C<connect()>
397  
398 $hash = {
399 target => E<lt>iname|inumberE<gt>, # eg: =my_personal_cloud
400 secret => $secret
401 };
402
403 $c = $xdi->connect($hash);
404
405 Given an I<iname>, the default behavior for XDI is to attempt to resolve the iname to it's
406 corresponding inumber using the iname resolution service at xri2xdi.net. This service
407 also returns the URI to the graph that is authoritative for said I<iname>, during testing and
408 development that often proves inconvenient so you can override this behavior
409  
410 $c->resolve(0);
411
412 Of course, if you do that, you will have to specify the URI of the graph to which you are
413 sending a query
414  
415 $c->server("http://example/=my_personal_cloud");
416
417 You may have noticed that we haven't actually I<connected> to anything yet. I reserve the right
418 to make checking the target graph for a valid link contract part of the connection process
419  
420 =head3 secret
421  
422 =over 2
423  
424 XDI security policy is currently under discussion by the XDI Technical Committee so the placeholder for a more robust policy is to use a shared secret. Please note that the policy allows for arbitrarily complex expressions and Javascript is proposed for the expression syntax. L<https://wiki.oasis-open.org/xdi/XdiPolicyExpression> As the policy matures, I expect to need to update the client
425  
426 =back
427  
428 Next step is to create an L<XDI::Message> object
429  
430 $msg = $c->message();
431
432 As usual, you can pass valid message constructor parameters to XDI::Connection::message
433  
434 $hash = {
435 link_contract => '=!1111'
436 };
437  
438 The C<link_contract> is the address of the node to which you have permissions. Note that you
439 not only have to have permission to that node, but you have to have permission to execute your
440 operation S<($get,$mod,$add,$del,$all)>
441  
442 The process of a external party negotiating a link contract is still under development so
443 an XDI server has the option of not enforcing link contracts. In such case, leave the
444 C<link_contract> parameter undefined and that statement will not be included as part of the
445 message. More information on link contracts can be found at L<XDI::Message>
446  
447 Compose the message that you intend to send to the target graph
448  
449 $msg->get('=!1111+tel');
450
451 An XDI message can only contain one type of operation, so it is an error to try to mix operations
452 in a message, but it is possible to send multiple statements of the same operation
453  
454 $msg->get('=!1111+tel');
455 $msg->get('=!1111+email');
456 $msg->get('=!1111+birthdate');
457
458 Each one of these operations composes an XDI statement. There is no order of execution for statements
459 in a message. This has little consequence for $get operations, but needs to be taken into consideration
460 for $add and $mod operations
461  
462 Once the message is composed, use the XDI::Connection object to C<post> the message to the target graph
463 C<post> performs an http post request to the server with the XDI message in the body.
464  
465 $graph = $c->post($msg);
466
467 The result is a JSON encoded representation of the nodes requested in the $get operation. Other
468 operations will return an empty hash {} upon success. Default behavior is to automatically convert
469 the JSON to a perl hash object
470  
471 =head1 SUBROUTINES/METHODS
472  
473 XDI and it's members support the common PERL OO-style syntax via AUTOLOAD
474  
475 =head2 Constructor
476  
477 $xdi = XDI->new($iname);
478  
479 $xdi = XDI->new({
480 'from' => '=tester,
481 'from_graph' => '@server'
482 });
483  
484 $xdi = XDI->new($ref);
485  
486 Constructs a new XDI object. Optional arguments consist of either a single iname|inumber string or a list of field => value pairs. The single argument will default values of from and from_graph to the same value.
487  
488 $xdi->from()
489
490 $xdi->from($val)
491  
492 Get/set C<from> value. C<from> is the identity of the entity making the XDI request
493  
494 $xdi->from_graph()
495  
496 $xdi->from_graph($val)
497  
498 Get/set C<from_graph> value. C<from_graph> is the identity of the B<graph> that is making the
499 XDI request. In the case of a PERL client, the distinction between C<from> and C<from_graph>
500 may be negligible, but could be significant when issues of authorized access via signed messages
501 are implemented
502  
503 =head2 connect
504  
505 $c = $xdi->connect()
506  
507 $c = $xdi->connect($hash)
508  
509 This method returns a XDI::Connection object. Any parameters passed to the method will be used to invoke the
510 XDI::Connection constructor.
511  
512 =head2 pick_xdi_tuple
513  
514 $tuple = pick_xdi_tuple($graph,[I<$subject>,I<$predicate>,I<$object>])
515  
516 C<$graph> is a perl hash object as returned by C<$c->post($msg)>
517  
518 I<$subject>,I<$predicate>,I<$object> are optional matching arguments (strings) used to match the returned tuple
519 Any one or two of the parameters may be C<undef>. Only the first matching tuple is returned
520  
521 pick_xdi_tuple returns an array reference [I<$subject>,I<$predicate>,I<$object>]
522  
523 =head2 tuples
524  
525 $tuples = tuples($graph,[I<$subject> | I<regex>,I<$predicate> | I<regex>,I<$object> | I<regex>])
526  
527 tuples returns an array of array references. Any of the match elements can be substituted with a regular expression.
528  
529 Usually the third element of the tuple is an array. If there is only 1 element to the array, the element is substituted for the array of 1 element
530  
531 =head2 get_literal
532  
533 get_literal($graph,I<$key>)
534 get_literal($graph,I<@key>)
535
536 get_literal is a convenience function to pull literals (I<subject>/!/I<literal>) from the graph. A single key or an array of keys is a valid parameter
537  
538 If an array of keys I<@key> is used, all of the values are placed into a single array that is returned
539  
540 =head2 get_equivalent
541  
542 get_equivalent($graph,$key)
543
544 get_equivalent is a convenience function to pull equivalance expressions (I<subject>/$is/I<equivalent>) from the graph.
545  
546 =head2 get_property
547  
548 get_property($graph,$key)
549
550 get_property is a convenience function to pull properties of I<subject> (I<subject>/()/I<property>) from the graph.
551  
552 =head2 get_context
553  
554 get_context($graph,$key)
555
556 get_context is a convenience function to pull the contexts of definitions (I<+(+def)>/$is()/[...]]) from the graph.
557  
558 =head1 AUTHOR
559  
560 Mark Horstmeier <solargroovey@gmail.com>
561  
562 =head1 COPYRIGHT AND LICENSE
563  
564 Copyright (C) 2007-2012 Kynetx, Inc.
565  
566 The perl XDI client is free software; you can redistribute it and/or
567 modify it under the terms of the GNU General Public License as
568 published by the Free Software Foundation; either version 2 of
569 the License, or (at your option) any later version.
570  
571 This program is distributed in the hope that it will be
572 useful, but WITHOUT ANY WARRANTY; without even the implied
573 warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
574 PURPOSE. See the GNU General Public License for more details.
575  
576 You should have received a copy of the GNU General Public
577 License along with this program; if not, write to the Free
578 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
579 MA 02111-1307 USA
580  
581  
582  
583  
↑ Summary XDI/Message.pm »