/
CRUD.pm
2180 lines (1695 loc) · 50 KB
/
CRUD.pm
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
=for Pod2Wiki {{Version|since=3.3.0}}
=head1 NAME
EPrints::Apache::CRUD - Create, read, update and delete via HTTP
=head1 SYNOPSIS
$crud = EPrints::Apache::CRUD->new(
repository => $repo,
request => $r,
datasetid => "eprint",
dataobjid => "23",
);
=head1 DESCRIPTION
The CRUD (Create/Read/Update/Delete) module provides the Web API for manipulating content on the server. The API is an AtomPub implementation that exposes Import and Export plugins via simple URLs and HTTP content type negotiation.
You should use the <link> entries in the repository's home page to locate the CRUD endpoint, as they may change in the future:
<link rel="Sword" href="https://myrepo/sword-app/servicedocument" />
<link rel="SwordDeposit" href="https://myrepo/id/contents" />
=head2 Examples
Create a new eprint based on a single file:
curl -X POST \
-i \
-u user:password \
-d 'Hello, World!' \
-H 'Content-Type: text/plain' \
https://myrepo/id/contents
HTTP/1.1 201 Created
Content-Type: application/atom+xml;charset=utf-8
...
Add a file to an existing eprint:
curl -X POST \
-i \
-u user:password \
-d 'Hello, World!' \
-H 'Content-Disposition: attachment; filename=hello.txt' \
-H 'Content-Type: text/plain' \
https://myrepo/id/eprint/23/contents
HTTP/1.1 201 Created
Content-Type: application/atom+xml;charset=utf-8
...
Get an eprint's metadata in Atom XML:
curl -X GET \
-i \
-u user:password \
-H 'Accept: application/atom+xml' \
https://myrepo/id/eprint/23
HTTP/1.1 200 OK
Content-Type: application/atom+xml;charset=utf-8
...
Get the list of contents (documents) of an eprint in Atom XML:
curl -X GET \
-i \
-u user:password \
-H 'Accept: application/atom+xml' \
https://myrepo/id/eprint/23/contents
HTTP/1.1 200 OK
Content-Type: application/atom+xml;charset=utf-8
...
You can find more examples in the F<tests/84_sword.t> unit test.
=head2 URI layout
These URIs are relative to your EPrints HTTP/HTTPs root.
=over 4
=item /id/contents GET,HEAD,OPTIONS,POST
Requires authentication.
GET a list of the eprints owned by the user. POST to create a new EPrint object.
=item /id/[datasetid]/[dataobjid] DELETE,GET,HEAD,OPTIONS,PUT
Requires authentication depending on user's privileges and object visibility.
GET an object's metadata or, for L<File|EPrints::DataObj::File> objects, the file content. PUT to replace the metadata and/or contents (see L</Updating complex objects using PUT>). If the object does not exist will attempt to create it with the given dataobjid (requires 'upsert' privilege).
=item /id/[datasetid]/[dataobjid]/contents DELETE,GET,HEAD,OPTIONS,POST,PUT
Requires authentication depending on user's privileges and object visibility.
GET the logical contents of the object: documents for eprints or files for documents. PUT to replace the existing contents or POST to add to the existing contents.
=back
=head2 HTTP Content Negotiation
GET/HEAD requests are processed using L<Export|EPrints::Plugin::Export> plugins. POST/PUT requests are processed using L<Import|EPrints::Plugin::Import> plugins.
The plugin used depends on the request's I<Accept> (GET/HEAD) or I<Content-Type> (POST/PUT) header and the type of object being acted on. For example, the following request:
GET /id/eprint/23 HTTP/1.1
Accept: application/vnd.eprints.data+xml
Will search for an Export plugin that accepts objects of type B<dataobj/eprint> and can produce output in the MIME type B<application/vnd.eprints.data+xml>. This will most likely be the L<EP3 XML|EPrints::Plugin::Export::XML> plugin.
In addition to the general plugin negotiation behaviour some special cases are supported to improve compatibility with Atom Pub/Web Browser clients:
=over 4
=item /id/eprint/...
Requesting L<EPrint|EPrints::DataObj::EPrint> objects as text/html will result in a 303 Redirect to the eprint object's abstract page or, if the eprint is not public, its L<View|EPrints::Plugin::Screen::EPrint::View> page.
=item /id/document/.../contents
Requesting the I</contents> of a L<Document|EPrints::DataObj::Document> object will return the content of the document's main file.
=item /id/file/...
Requesting a L<File|EPrints::DataObj::File> object with no I<Accept> header (or B<*/*>) will return the file's content.
=item POST /id/.../contents
When creating new records via POST, content negotiation is performed against the Import plugins.
If no Import plugin supports the I<Content-Type> header the content will be treated as B<application/octet-stream> and stored in a new object. The resulting Atom entry will describe the new object (e.g. the I<eprint> object in which the new I<document> and I<file> objects were created).
Otherwise, the result will depend on the Import plugin's output. Import plugins may produce a single object, multiple objects or an object plus content file(s).
=item Content-Type header
If no I<Content-Type> header is given the MIME type defaults to B<application/octet-stream> for POSTs and PUTs.
=item Content-Disposition header
If the I<Content-Disposition> header is missing or does not contain a I<filename> parameter the filename defaults to F<main.bin> for POSTs and PUTs.
=back
=head2 Updating complex objects using PUT
Eprint objects contain zero or more documents, which each contain zero or more files. When you update (PUT) an eprint object the contained documents will only be replaced if the Import plugin defines new documents e.g. the Atom Import plugin will never define new documents so PUTing Atom content will only update the eprint's metadata. PUTing L<EP3 XML|EPrints::Plugin::Export::XML> will replace the documents if you include a <documents> XML element.
PUTing to I</contents> will always replace all contents - PUTing to I</eprint/23/contents> is equivalent to I<DELETE /eprint/23/contents> then I<POST /eprint/23/contents>.
=head2 PUT/DELETE from Javascript
=for MediaWiki {{Available|since=3.3.9}}
Web browsers only allow GET and POST requests. To perform other requests use the 'X-Method' header with POST to specify the actual method you want:
POST /id/eprint/23 HTTP/1.1
X-Method: PUT
...
=head2 Upserting objects with PUT
=for MediaWiki {{Available|since=3.3.9}}
If you have the I<upsert> privilege objects will be created on demand, otherwise attempting to PUT to a non-existent object will result in an error.
=head1 METHODS
=over 4
=cut
package EPrints::Apache::CRUD;
use EPrints::Const qw( :http );
use MIME::Base64;
use HTTP::Headers::Util;
use Digest::MD5;
use EPrints::Apache::Auth;
use Apache2::Access;
our $PACKAGING_PREFIX = "sword:";
use constant {
CRUD_SCOPE_USER_CONTENTS => 1,
CRUD_SCOPE_DATASET => 2,
CRUD_SCOPE_DATAOBJ => 3,
CRUD_SCOPE_FIELD => 4,
CRUD_SCOPE_CONTENTS => 5,
CRUD_SCOPE_SERVICEDOCUMENT => 6,
};
use strict;
my %CONTENTSMAP = (
"EPrints::DataObj::EPrint" => "documents",
"EPrints::DataObj::Document" => "files",
);
sub new
{
my( $class, %self ) = @_;
my $self = bless \%self, $class;
my $rc = $self->process_headers;
$self->request->status( $rc ), return if $rc != OK;
$self{options} = [qw( GET HEAD OPTIONS )];
# servicedocument FIXME
return $self if !exists $self{datasetid};
my $repo = $self{repository};
# /id/FOO...
if( defined $self{datasetid} )
{
$self{dataset} = $repo->dataset( $self{datasetid} );
if( !defined $self{dataset} )
{
$self{request}->status( HTTP_NOT_FOUND );
return;
}
$self{options} = [qw( GET HEAD POST OPTIONS )];
$self{scope} = CRUD_SCOPE_DATASET;
}
# /id/contents
else
{
$self{dataset} = $repo->dataset( "eprint" );
$self{options} = [qw( GET HEAD POST OPTIONS )];
$self{scope} = CRUD_SCOPE_USER_CONTENTS;
}
# /id/FOO/BAR
if( defined $self{dataobjid} )
{
my @relations;
if( $self{dataset}->base_id eq "document" )
{
($self{dataobjid}, @relations) = split /\./, $self{dataobjid};
@relations = grep { length($_) } @relations;
}
$self{dataobj} = $self{dataset}->dataobj( $self{dataobjid} );
# resolve 11.hassmallThumbnailVersion
$self{dataobj} = $self->resolve_relations( $self{dataobj}, @relations );
# adjust /id/eprint/23 to /id/archive/23
$self{dataset} = $self{dataobj}->get_dataset if defined $self{dataobj};
$self{options} = [qw( GET HEAD PUT PATCH OPTIONS )];
$self{scope} = CRUD_SCOPE_DATAOBJ;
}
# /id/FOO/BAR/xxx
if( defined $self{fieldid} )
{
if( $self{fieldid} eq "contents" )
{
$self{options} = [qw( GET HEAD POST PUT OPTIONS )];
$self{scope} = CRUD_SCOPE_CONTENTS;
my $fieldid = $CONTENTSMAP{ref($self->dataobj)};
if( !defined $fieldid )
{
$self{request}->status( HTTP_NOT_FOUND );
return;
}
$self{field} = $self{dataset}->field( $fieldid );
$self{dataset} = $repo->dataset(
$self{field}->property( "datasetid" )
);
}
elsif( !$self{dataset}->has_field( $self{fieldid} ) )
{
$self{request}->status( HTTP_NOT_FOUND );
return;
}
else
{
$self{field} = $self{dataset}->field( $self{fieldid} );
$self{options} = [qw( GET HEAD PUT OPTIONS )];
$self{scope} = CRUD_SCOPE_FIELD;
}
}
if( !defined $self{plugin} )
{
$self{plugin} = $self->content_negotiate_best_plugin;
}
return $self;
}
=item $repo = $crud->repository()
Returns the current repository.
=cut
sub repository { $_[0]->{repository} }
=item $r = $crud->request()
Returns the current L<Apache2::RequestUtil>.
=cut
sub request { $_[0]->{request} }
=item $method = $crud->method()
Returns the HTTP method.
=cut
sub method { $_[0]->{method} }
=item $scope = $crud->scope()
Returns the scope of the action being performed.
=cut
sub scope { $_[0]->{scope} }
=item $dataset = $crud->dataset()
Returns the current dataset (if any).
=cut
sub dataset { $_[0]->{dataset} }
=item $dataobj = $crud->dataobj()
Returns the current dataobj (if any).
=cut
sub dataobj { $_[0]->{dataobj} }
=item $field = $crud->field()
Returns the current field (if available);
=cut
sub field { $_[0]->{field} }
=item $headers = $crud->headers()
Get the processed headers.
=cut
sub headers { $_[0]->{headers} }
=item @verbs = $crud->options()
Returns the available HTTP verbs for the current request.
=cut
sub options { @{$_[0]->{options}} }
=item $plugin = $crud->plugin()
Returns the current plugin (if available).
=cut
sub plugin { $_[0]->{plugin} }
=item $bool = $crud->is_write()
Returns true if the request is not a read-only method.
=cut
sub is_write { $_[0]->method !~ /^GET|HEAD|OPTIONS$/ }
=item $accept_type = $crud->accept_type()
Returns the EPrints type for the current request.
=cut
sub accept_type
{
my( $self ) = @_;
my $accept_type = $self->dataset->base_id;
if(
$self->is_write ||
$self->scope == CRUD_SCOPE_DATAOBJ ||
$self->scope == CRUD_SCOPE_SERVICEDOCUMENT
)
{
$accept_type = "dataobj/".$accept_type;
}
else
{
$accept_type = "list/".$accept_type;
}
return $accept_type;
}
=item $rc = $crud->check_packaging()
Check the Packaging header is ok, if given.
=cut
sub check_packaging
{
my( $self ) = @_;
my $headers = $self->headers;
if( $headers->{packaging} && !defined $self->plugin )
{
return $self->sword_error(
status => HTTP_BAD_REQUEST,
href => "http://purl.org/net/sword/error/ErrorContent",
summary => "No support for packaging '$headers->{packaging}'",
);
}
return OK;
}
=item $dataobj = $crud->resolve_relations( $dataobj [, @relations ] )
Resolve the relation path from $dataobj and return the resulting dataobj.
Returns undef if there is no such related object.
=cut
sub resolve_relations
{
my( $self, $dataobj, @relations ) = @_;
foreach my $r (@relations)
{
last if !defined $dataobj;
$r =~ s/^has(.+)$/is$1Of/;
$dataobj = $dataobj->search_related( $r )->item( 0 );
}
return $dataobj;
}
sub _priv
{
my( $self ) = @_;
my $r = $self->request;
my $dataset = $self->dataset;
my $dataobj = $self->dataobj;
my $plugin = $self->plugin;
my $field = $self->field;
my $priv;
# /id/xx/yy/contents
if( $self->scope eq CRUD_SCOPE_CONTENTS )
{
$priv = $self->is_write ? "edit" : "view";
$dataobj = $dataobj->parent
if $dataobj->isa( "EPrints::DataObj::File" );
$dataobj = $dataobj->parent
if $dataobj->isa( "EPrints::DataObj::Document" );
$dataset = $dataobj->get_dataset;
}
elsif( $self->method eq "POST" )
{
$priv = "create";
}
elsif( $self->method eq "PUT" )
{
if( $self->scope == CRUD_SCOPE_DATAOBJ && !defined $dataobj )
{
$priv = "upsert";
}
else
{
$priv = "edit";
}
}
elsif( $self->method eq "PATCH" )
{
$priv = "edit";
}
elsif( $self->method eq "DELETE" )
{
$priv = "destroy";
}
elsif( defined($plugin) && $plugin->get_subtype ne "SummaryPage" )
{
$priv = "export";
}
else
{
$priv = "view";
}
if( $dataset->base_id eq "eprint" && $priv eq "create" )
{
$priv = "create_eprint";
}
elsif( $self->scope eq CRUD_SCOPE_USER_CONTENTS && $dataset->base_id eq "eprint" && $priv eq "view" )
{
$priv = "items";
}
elsif( $dataset->id ne $dataset->base_id )
{
return(
join('/', $dataset->base_id, $dataset->id, $priv ),
join('/', $dataset->base_id, $priv ),
);
}
else
{
$priv = join('/', $dataset->base_id, $priv );
}
return $priv;
}
# authentication
sub authen
{
my( $self ) = @_;
my $r = $self->request;
my $repo = $self->repository;
my $dataset = $self->dataset;
my $dataobj = $self->dataobj;
my $plugin = $self->plugin;
# POST, PUT, DELETE must authenticate
if( $self->is_write )
{
return EPrints::Apache::Auth::authen( $r );
}
# a staff-plugin implicitly requires a user
if( defined($plugin) && $plugin->param( "visible" ) eq "staff" )
{
return EPrints::Apache::Auth::authen( $r );
}
# /id/contents implicitly requires a user
if( $self->scope eq CRUD_SCOPE_USER_CONTENTS )
{
return EPrints::Apache::Auth::authen( $r );
}
my @privs = $self->_priv;
if( defined $dataobj )
{
foreach my $priv (@privs)
{
return OK if $dataobj->permit( $priv );
}
}
else
{
foreach my $priv (@privs)
{
return OK if $repo->allow_anybody( $priv );
}
}
return EPrints::Apache::Auth::authen( $r );
}
# authorisation
sub authz
{
my( $self ) = @_;
my $r = $self->request;
my $repo = $self->repository;
my $dataset = $self->dataset;
my $dataobj = $self->dataobj;
my $plugin = $self->plugin;
my $user = $repo->current_user;
if( defined($plugin) && $plugin->param( "visible" ) eq "staff" )
{
return HTTP_FORBIDDEN if !defined $user || !$user->is_staff;
}
my @privs = $self->_priv;
if( defined $dataobj )
{
foreach my $priv (@privs)
{
return OK if $dataobj->permit( $priv, $user );
}
}
elsif( defined $user )
{
foreach my $priv (@privs)
{
return OK if $user->allow( $priv );
}
}
else
{
foreach my $priv (@privs)
{
return OK if $repo->allow_anybody( $priv );
}
}
return HTTP_FORBIDDEN;
}
=item $list = $crud->parse_input( $plugin, $f [, %params ] )
Parse the content submitted by the user using the given $plugin. $f is called by epdata_to_dataobj to convert epdata to a dataobj. %params are passed to the plugin's input_fh method.
Returns undef on error.
=cut
sub _read_content
{
my( $self ) = @_;
my $r = $self->request;
my $repo = $self->repository;
my $headers = $self->headers;
my $ctx = $headers->{content_md5} ? Digest::MD5->new : undef;
my $tmpfile = File::Temp->new( SUFFIX => $headers->{extension} );
binmode($tmpfile);
my $len = 0;
while($r->read(my $buffer, 4096)) {
$len += length($buffer);
$ctx->add( $buffer ) if defined $ctx;
print $tmpfile $buffer;
}
seek($tmpfile,0,0);
if( defined $ctx && $ctx->hexdigest ne $headers->{content_md5} )
{
$self->sword_error(
status => HTTP_PRECONDITION_FAILED,
href => "http://purl.org/net/sword/error/ErrorChecksumMismatch",
summary => "MD5 digest mismatch between headers and content",
);
return undef;
}
return $tmpfile;
}
sub parse_input
{
my( $self, $plugin, $f, %params ) = @_;
my $repo = $self->repository;
my $headers = $self->headers;
my @messages;
my $count = 0;
$plugin->set_handler( EPrints::CLIProcessor->new(
message => sub { push @messages, $_[1] },
epdata_to_dataobj => sub { ++$count; &$f },
) );
my $tmpfile = $self->_read_content();
return undef if !defined $tmpfile;
my %content_type_params;
for(keys %{$headers->{content_type_params}})
{
next if !$plugin->has_argument( $_ );
$content_type_params{$_} = $headers->{content_type_params}->{$_};
}
my $list = eval { $plugin->input_fh(
%content_type_params,
dataset => $self->dataset,
fh => $tmpfile,
filename => $headers->{filename},
mime_type => $headers->{mime_type},
content_type => $headers->{content_type},
actions => $headers->{actions},
%params,
) };
if( !defined $list )
{
$self->plugin_error( $plugin, \@messages );
return undef;
}
elsif( $count == 0 )
{
$plugin->handler->message( "error", "Import plugin didn't create anything" );
$self->plugin_error( $plugin, \@messages );
return undef;
}
return $list;
}
sub create_dataobj
{
my( $self, $owner, $epdata ) = @_;
$epdata = {} if !defined $epdata;
my $repo = $self->repository;
my $dataset = $self->dataset;
local $repo->{config}->{enable_import_fields} = 1;
$epdata->{$dataset->key_field->name} = $self->{dataobjid};
if( $dataset->base_id eq "eprint" )
{
$epdata->{userid} = $owner->id;
$epdata->{eprint_status} = "inbox";
}
return $dataset->create_dataobj( $epdata );
}
=item @plugins = $crud->import_plugins( [ %params ] )
Returns all matching import plugins against %params ordered by descending 'q' score.
=cut
sub import_plugins
{
my( $self, %params ) = @_;
my $user = $self->repository->current_user;
if( defined $user && !$user->is_staff )
{
$params{is_visible} = "all";
}
my @plugins = $self->repository->get_plugins(
type => "Import",
can_produce => $self->accept_type,
%params,
);
my %qs = map { $_ => ($_->param( "qs" ) || 0) } @plugins;
my %ids = map { $_ => $_->get_id } @plugins;
return sort {
$qs{$b} <=> $qs{$a} || $ids{$a} cmp $ids{$b}
} @plugins;
}
=item @plugins = $crud->export_plugins( [ %params ] )
Returns all matching export plugins against %params ordered by descending 'q' score.
=cut
sub export_plugins
{
my( $self, %params ) = @_;
my $user = $self->repository->current_user;
if( defined $user && !$user->is_staff )
{
$params{is_visible} = "all";
}
my @plugins = $self->repository->get_plugins(
type => "Export",
can_accept => $self->accept_type,
%params,
);
my %qs = map { $_ => ($_->param( "qs" ) || 0) } @plugins;
my %ids = map { $_ => $_->get_id } @plugins;
return sort {
$qs{$b} <=> $qs{$a} || $ids{$a} cmp $ids{$b}
} @plugins;
}
=item $plugin = $crud->content_negotiate_best_plugin()
Work out the best plugin to export/update an object based on the client-headers.
=cut
sub content_negotiate_best_plugin
{
my( $self ) = @_;
my $r = $self->request;
my $repo = $self->repository;
my $dataset = $self->dataset;
my $field = $self->field;
my $headers = $self->headers;
return undef if $self->method eq "DELETE";
my $accept_type = $self->accept_type;
if( defined(my $package = $headers->{packaging}) )
{
my $plugin;
if( $self->is_write )
{
($plugin) = $self->import_plugins(
can_accept => $PACKAGING_PREFIX.$package,
can_action => $headers->{actions},
);
}
else
{
($plugin) = $self->export_plugins(
can_produce => $PACKAGING_PREFIX.$package,
);
}
return $plugin;
}
my @plugins;
if( $self->is_write )
{
@plugins = $self->import_plugins(
can_action => $headers->{actions},
);
}
else
{
@plugins = $self->export_plugins();
}
my %pset;
foreach my $plugin ( @plugins )
{
my $mimetype = $plugin->get_type eq "Export" ?
$plugin->param( "produce" ) :
$plugin->param( "accept" );
$mimetype = join ',', @$mimetype;
for( HTTP::Headers::Util::split_header_words( $mimetype ) )
{
my( $type, undef, %params ) = @$_;
push @{$pset{$type}}, {
%params,
plugin => $plugin,
q => $plugin->param( "qs" ),
id => $plugin->get_id,
};
}
}
# sort plugins internally by q then id
for(values(%pset))
{
@$_ = sort { $b->{q} <=> $a->{q} || $a->{id} cmp $b->{id} } @$_;
}
# sort supported types by the highest plugin score
my @pset_order = sort {
$pset{$b}->[0]->{q} <=> $pset{$a}->[0]->{q}
} keys %pset;
my $accept;
if( $self->is_write )
{
$accept = $r->headers_in->{'Content-Type'};
}
else
{
# summary page is higher priority than anything else for /id/eprint/23
# and /id/contents
if( ( $self->scope == CRUD_SCOPE_DATAOBJ && $self->{dataset}->base_id ne "subject" ) || $self->scope == CRUD_SCOPE_USER_CONTENTS )
{
my $plugin = $repo->plugin( "Export::SummaryPage" );
my $mimetype = $plugin->param( "produce" );
$mimetype = join ',', @$mimetype;
for( HTTP::Headers::Util::split_header_words( $mimetype ) )
{
my( $type, undef, %params ) = @$_;
unshift @pset_order, $type;
unshift @{$pset{$type}}, {
charset => 'utf-8',
q => $plugin->param( "qs" ),
plugin => $plugin,
};
}
}
$accept = $r->headers_in->{Accept} || "*/*";
}
my @accept = parse_media_range( $accept || "" );
my $match;
CHOICE: foreach my $choice ( @accept )
{
my( $mime_type, undef, %params ) = @$choice;
my( $type, $subtype ) = split '/', $mime_type;
# find matching entries by mime-type
if( exists $pset{$mime_type} )
{
# pick the best plugin based on parameters and then plugin qs
my $plugins = $pset{$mime_type};
for(keys %params) {
next if $_ eq "q";
foreach my $match (@$plugins) {
$match->{q}++
if exists($match->{$_}) && $match->{$_} eq $params{$_};
}
}
$match = (sort { $b->{q} <=> $a->{q} || $a->{id} cmp $b->{id} } @$plugins)[0]->{plugin};
$r->pnotes->{mime_type} = $mime_type;
last CHOICE;
}
# */*
elsif( $type eq '*' && $subtype eq '*' )
{
$match = $pset{$pset_order[0]}->[0]->{plugin};
$r->pnotes->{mime_type} = $mime_type;
last CHOICE;
}
# text/*
elsif( $subtype eq '*' )
{
for(@pset_order)
{
if( m#^$type/# )
{
$match = $pset{$_}->[0]->{plugin};
$r->pnotes->{mime_type} = $mime_type;
last CHOICE;
}
}
}
}
return $match;
}
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
sub parse_media_range
{
my( $media_range ) = @_;
my @accept = HTTP::Headers::Util::split_header_words( $media_range );
for(@accept)
{
my( $mime_type, undef, %params ) = @$_;
$params{'mime_type'} = $mime_type;
$params{q} = 1 if !defined $params{q};
$_ = \%params;
}
@accept = sort {
# q-scores
$b->{q} <=> $a->{q} ||
# text/html is higher than text/*
$a->{mime_type} cmp $b->{mime_type} ||
# text/html;level=1 is higher than text/html
scalar(keys %$b) <=> scalar(keys %$a)
} @accept;
return map { [ delete $_->{mime_type}, undef, %$_ ] } @accept;
}
sub handler
{
my( $self ) = @_;
my $r = $self->request;