adding opac bookbag output type
[Evergreen.git] / Open-ILS / src / perlmods / OpenILS / WWW / SuperCat.pm
1 package OpenILS::WWW::SuperCat;
2 use strict; use warnings;
3
4 use Apache2 ();
5 use Apache2::Log;
6 use Apache2::Const -compile => qw(OK REDIRECT DECLINED :log);
7 use APR::Const    -compile => qw(:error SUCCESS);
8 use Apache2::RequestRec ();
9 use Apache2::RequestIO ();
10 use Apache2::RequestUtil;
11 use CGI;
12 use Data::Dumper;
13
14 use OpenSRF::EX qw(:try);
15 use OpenSRF::Utils qw/:datetime/;
16 use OpenSRF::System;
17 use OpenSRF::AppSession;
18 use XML::LibXML;
19
20 use Unicode::Normalize;
21 use OpenILS::Utils::Fieldmapper;
22 use OpenILS::WWW::SuperCat::Feed;
23
24
25 # set the bootstrap config when this module is loaded
26 my ($bootstrap, $supercat, $actor, $parser, $search);
27
28 sub import {
29         my $self = shift;
30         $bootstrap = shift;
31 }
32
33
34 sub child_init {
35         OpenSRF::System->bootstrap_client( config_file => $bootstrap );
36         $supercat = OpenSRF::AppSession->create('open-ils.supercat');
37         $actor = OpenSRF::AppSession->create('open-ils.actor');
38         $search = OpenSRF::AppSession->create('open-ils.search');
39         $parser = new XML::LibXML;
40 }
41
42 sub oisbn {
43
44         my $apache = shift;
45         return Apache2::Const::DECLINED if (-e $apache->filename);
46
47         (my $isbn = $apache->path_info) =~ s{^.*?([^/]+)$}{$1}o;
48
49         my $list = $supercat
50                 ->request("open-ils.supercat.oisbn", $isbn)
51                 ->gather(1);
52
53         print "Content-type: application/xml; charset=utf-8\n\n";
54         print "<?xml version='1.0' encoding='UTF-8' ?>\n";
55
56         unless (exists $$list{metarecord}) {
57                 print '<idlist/>';
58                 return Apache2::Const::OK;
59         }
60
61         print "<idlist metarecord='$$list{metarecord}'>\n";
62
63         for ( keys %{ $$list{record_list} } ) {
64                 (my $o = $$list{record_list}{$_}) =~s/^(\S+).*?$/$1/o;
65                 print "  <isbn record='$_'>$o</isbn>\n"
66         }
67
68         print "</idlist>\n";
69
70         return Apache2::Const::OK;
71 }
72
73 sub unapi {
74
75         my $apache = shift;
76         return Apache2::Const::DECLINED if (-e $apache->filename);
77
78         print "Content-type: application/xml; charset=utf-8\n";
79         
80         my $cgi = new CGI;
81
82         my $uri = $cgi->param('uri') || '';
83         my $base = $cgi->url;
84         my $host = $cgi->virtual_host || $cgi->server_name;
85
86         my $format = $cgi->param('format');
87         my ($id,$type,$command) = ('','','');
88
89         if (!$format) {
90                 if ($uri =~ m{^tag:[^:]+:([^\/]+)/(\d+)}o) {
91                         $id = $2;
92                         $type = 'record';
93                         $type = 'metarecord' if ($1 =~ /^m/o);
94
95                         my $list = $supercat
96                         ->request("open-ils.supercat.$type.formats")
97                                 ->gather(1);
98
99                         print "\n";
100
101                         my $body =
102                                 "<formats>
103                                  <uri>$uri</uri>
104                                    <format>
105                                      <name>opac</name>
106                                      <type>text/html</type>
107                                    </format>";
108
109                         for my $h (@$list) {
110                                 my ($type) = keys %$h;
111                                 $body .= "<format><name>$type</name><type>application/$type+xml</type>";
112
113                                 for my $part ( qw/namespace_uri docs schema_location/ ) {
114                                         $body .= "<$part>$$h{$type}{$part}</$part>"
115                                                 if ($$h{$type}{$part});
116                                 }
117                                 
118                                 $body .= '</format>';
119                         }
120
121                         $body .= "</formats>\n";
122
123                         $apache->custom_response( 300, $body);
124                         return 300;
125                 } else {
126                         my $list = $supercat
127                                 ->request("open-ils.supercat.record.formats")
128                                 ->gather(1);
129                                 
130                         push @$list,
131                                 @{ $supercat
132                                         ->request("open-ils.supercat.metarecord.formats")
133                                         ->gather(1);
134                                 };
135
136                         my %hash = map { ( (keys %$_)[0] => (values %$_)[0] ) } @$list;
137                         $list = [ map { { $_ => $hash{$_} } } sort keys %hash ];
138
139                         print "\n<formats>
140                                    <format>
141                                      <name>opac</name>
142                                      <type>text/html</type>
143                                    </format>";
144
145                         for my $h (@$list) {
146                                 my ($type) = keys %$h;
147                                 print "<format><name>$type</name><type>application/$type+xml</type>";
148
149                                 for my $part ( qw/namespace_uri docs schema_location/ ) {
150                                         print "<$part>$$h{$type}{$part}</$part>"
151                                                 if ($$h{$type}{$part});
152                                 }
153                                 
154                                 print '</format>';
155                         }
156
157                         print "</formats>\n";
158
159
160                         return Apache2::Const::OK;
161                 }
162         }
163
164                 
165         if ($uri =~ m{^tag:[^:]+:([^\/]+)/(\d+)}o) {
166                 $id = $2;
167                 $type = 'record';
168                 $type = 'metarecord' if ($1 =~ /^m/o);
169                 $command = 'retrieve';
170         }
171
172         if ($format eq 'opac') {
173                 print "Location: $base/../../en-US/skin/default/xml/rresult.xml?m=$id\n\n"
174                         if ($type eq 'metarecord');
175                 print "Location: $base/../../en-US/skin/default/xml/rdetail.xml?r=$id\n\n"
176                         if ($type eq 'record');
177                 return 302;
178         }
179
180         print "\n" . $supercat->request("open-ils.supercat.$type.$format.$command",$id)->gather(1);
181
182         return Apache2::Const::OK;
183 }
184
185 sub supercat {
186
187         my $apache = shift;
188         return Apache2::Const::DECLINED if (-e $apache->filename);
189
190         my $path = $apache->path_info;
191
192         my $cgi = new CGI;
193         my $base = $cgi->url;
194
195         my ($id,$type,$format,$command) = reverse split '/', $path;
196
197         print "Content-type: application/xml; charset=utf-8\n";
198         
199         if ( $path =~ m{^/formats(?:/([^\/]+))?$}o ) {
200                 if ($1) {
201                         my $list = $supercat
202                                 ->request("open-ils.supercat.$1.formats")
203                                 ->gather(1);
204
205                         print "\n";
206
207                         print "<formats>
208                                    <format>
209                                      <name>opac</name>
210                                      <type>text/html</type>
211                                    </format>";
212
213                         for my $h (@$list) {
214                                 my ($type) = keys %$h;
215                                 print "<format><name>$type</name><type>application/$type+xml</type>";
216
217                                 for my $part ( qw/namespace_uri docs schema_location/ ) {
218                                         print "<$part>$$h{$type}{$part}</$part>"
219                                                 if ($$h{$type}{$part});
220                                 }
221                                 
222                                 print '</format>';
223                         }
224
225                         print "</formats>\n";
226
227                         return Apache2::Const::OK;
228                 }
229
230                 my $list = $supercat
231                         ->request("open-ils.supercat.record.formats")
232                         ->gather(1);
233                                 
234                 push @$list,
235                         @{ $supercat
236                                 ->request("open-ils.supercat.metarecord.formats")
237                                 ->gather(1);
238                         };
239
240                 my %hash = map { ( (keys %$_)[0] => (values %$_)[0] ) } @$list;
241                 $list = [ map { { $_ => $hash{$_} } } sort keys %hash ];
242
243                 print "\n<formats>
244                            <format>
245                              <name>opac</name>
246                              <type>text/html</type>
247                            </format>";
248
249                 for my $h (@$list) {
250                         my ($type) = keys %$h;
251                         print "<format><name>$type</name><type>application/$type+xml</type>";
252
253                         for my $part ( qw/namespace_uri docs schema_location/ ) {
254                                 print "<$part>$$h{$type}{$part}</$part>"
255                                         if ($$h{$type}{$part});
256                         }
257                         
258                         print '</format>';
259                 }
260
261                 print "</formats>\n";
262
263
264                 return Apache2::Const::OK;
265         }
266
267         if ($format eq 'opac') {
268                 print "Location: $base/../../en-US/skin/default/xml/rresult.xml?m=$id\n\n"
269                         if ($type eq 'metarecord');
270                 print "Location: $base/../../en-US/skin/default/xml/rdetail.xml?r=$id\n\n"
271                         if ($type eq 'record');
272                 return 302;
273         }
274
275         print "\n" . $supercat->request("open-ils.supercat.$type.$format.$command",$id)->gather(1);
276
277         return Apache2::Const::OK;
278 }
279
280
281 sub bookbag_feed {
282         my $apache = shift;
283         return Apache2::Const::DECLINED if (-e $apache->filename);
284
285         my $cgi = new CGI;
286         (my $unapi = $cgi->url) =~ s{[^/]+/?$}{unapi};
287
288         my $year = (gmtime())[5];
289
290         my $host = $cgi->virtual_host || $cgi->server_name;
291         my $path = $apache->path_info;
292         my $base = $cgi->url;
293
294         my ($id,$type) = reverse split '/', $path;
295
296         my $bucket = $actor->request("open-ils.actor.container.public.flesh", 'biblio', $id)->gather(1);
297         my $bucket_tag = "tag:$host,$year:record_bucket/$id";
298
299         if ($type eq 'opac') {
300                 print "Location: $base/../../../opac/en-US/skin/default/xml/rresult.xml?rt=list&" .
301                         join('&', map { "rl=" . $_->target_biblio_record_entry } @{ $bucket->items }) .
302                         "\n\n";
303                 return Apache2::Const::OK;
304         }
305
306         my $feed = create_record_feed(
307                 $type,
308                 [ map { $_->target_biblio_record_entry } @{ $bucket->items } ],
309                 $unapi,
310         );
311
312         $feed->title("Items in Book Bag #".$bucket->id);
313         $feed->creator($host);
314         $feed->update_ts(gmtime_ISO8601());
315
316         $feed->link(atom => $base . "/bookbag/atom/$id");
317         $feed->link(rss2 => $base . "/bookbag/rss2/$id");
318         $feed->link(html => $base . "/bookbag/html/$id");
319
320         print "Content-type: application/xml; charset=utf-8\n\n";
321         print entityize($feed->toString) . "\n";
322
323         return Apache2::Const::OK;
324 }
325
326 sub opensearch_osd {
327         my $version = shift;
328         my $class = shift;
329         my $base = shift;
330
331         if ($version eq '1.0') {
332                 print <<OSD;
333 Content-type: application/opensearchdescription+xml; charset=utf-8
334
335 <?xml version="1.0" encoding="UTF-8"?>
336 <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearchdescription/1.0/">
337   <Url>$base/1.0/-/$class/-/{searchTerms}?startPage={startPage}&amp;startIndex={startIndex}&amp;count={count}</Url>
338   <Format>http://a9.com/-/spec/opensearchrss/1.0/</Format>
339   <ShortName>$class</ShortName>
340   <LongName>Search by $class</LongName>
341   <Description>Search the OPAC by $class.</Description>
342   <Tags>book library</Tags>
343   <SampleSearch>harry+potter</SampleSearch>
344   <Developer>Mike Rylander for GPLS/PINES</Developer>
345   <Contact>feedback\@open-ils.org</Contact>
346   <SyndicationRight>open</SyndicationRight>
347   <AdultContent>false</AdultContent>
348 </OpenSearchDescription>
349 OSD
350         } else {
351                 print <<OSD;
352 Content-type: application/opensearchdescription+xml; charset=utf-8
353
354 <?xml version="1.0" encoding="UTF-8"?>
355 <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">
356   <ShortName>$class</ShortName>
357   <Description>Search the OPAC by $class.</Description>
358   <Tags>book library</Tags>
359   <Url type="application/atom+xml"
360        method="post"
361        template="$base/1.1/-/$class/atom/{searchTerms}">
362     <Param name="startPage" value="{startPage?}"/>
363     <Param name="startIndex" value="{startIndex?}"/>
364     <Param name="count" value="{count?}"/>
365   </Url>
366   <Url type="application/rss+xml"
367        method="post"
368        template="$base/1.1/-/$class/rss2/{searchTerms}">
369     <Param name="startPage" value="{startPage?}"/>
370     <Param name="startIndex" value="{startIndex?}"/>
371     <Param name="count" value="{count?}"/>
372   </Url>
373   <Url type="application/mods+xml"
374        method="post"
375        template="$base/1.1/-/$class/mods/{searchTerms}">
376     <Param name="startPage" value="{startPage?}"/>
377     <Param name="startIndex" value="{startIndex?}"/>
378     <Param name="count" value="{count?}"/>
379   <LongName>Search by $class</LongName>
380   <Query role="example" searchTerms="harry+potter" />
381   <Developer>Mike Rylander for GPLS/PINES</Developer>
382   <SyndicationRight>open</SyndicationRight>
383   <AdultContent>false</AdultContent>
384   <Language>en-us</Language>
385   <OutputEncoding>UTF-8</OutputEncoding>
386   <InputEncoding>UTF-8</InputEncoding>
387 </OpenSearchDescription>
388 OSD
389         }
390
391         return Apache2::Const::OK;
392 }
393
394 sub opensearch_feed {
395         my $apache = shift;
396         return Apache2::Const::DECLINED if (-e $apache->filename);
397
398         my $cgi = new CGI;
399         (my $unapi = $cgi->url) =~ s{[^/]+/?$}{unapi};
400
401         my $year = (gmtime())[5];
402
403         my $host = $cgi->virtual_host || $cgi->server_name;
404         my $base = $cgi->url;
405         my $path = $apache->path_info;
406
407         if ($path =~ m{^/?(1\.\d{1})/([^/]+)/osd.xml}o) {
408                 
409                 my $version = $1;
410                 my $class = $2;
411
412                 if ($class eq '-') {
413                         $class = 'keyword';
414                 }
415
416                 return opensearch_osd($version, $class, $base);
417         }
418
419
420         my $page = $cgi->param('startPage') || 1;
421         my $offset = $cgi->param('startIndex') || 1;
422         my $limit = $cgi->param('count') || 10;
423
424         if ($page > 1) {
425                 $offset = ($page - 1) * $limit;
426         } else {
427                 $offset -= 1;
428         }
429
430         my ($terms,$class,$type,$org,$version) = reverse split '/', $path;
431
432         if ($org !~ /^[1-9]{1}[0-9]*$/o) {
433                 $org = 1;
434         }
435
436         if ($version eq '1.0') {
437                 $type = 'rss2';
438         } elsif ($type eq '-') {
439                 $type = 'atom';
440         }
441
442         $class = 'keyword' if ($class eq '-');
443         $terms =~ s/\+/ /go;
444
445         warn "searching for $class -> [$terms] via OS $version, response type $type";
446
447         my $recs = $search->request(
448                 'open-ils.search.biblio.record.class.search' => $class,
449                 { term          => $terms,
450                   org_unit      => $org,
451                   limit         => $limit,
452                   offset        => $offset,
453                 }
454         )->gather(1);
455
456         my $feed = create_record_feed(
457                 $type,
458                 [ map { $_->[0] } @{$recs->{ids}} ],
459                 $unapi,
460         );
461
462 =head
463         my $bucket = $actor->request("open-ils.actor.container.public.flesh", 'biblio', $id)->gather(1);
464         my $bucket_tag = "tag:$host,$year:record_bucket/$id";
465
466         my $feed = create_record_feed(
467                 $type,
468                 [ map { $_->target_biblio_record_entry } @{ $bucket->items } ],
469                 $unapi,
470         );
471
472         $feed->title("Items in Book Bag #".$bucket->id);
473         $feed->creator($host);
474         $feed->update_ts(gmtime_ISO8601());
475
476         $feed->link(atom => $id);
477         $feed->link(rss2 => $id);
478         $feed->link(html => $id);
479
480 =cut
481
482         $feed->_create_node(
483                 $feed->{item_xpath},
484                 'http://a9.com/-/spec/opensearch/1.1/',
485                 'totalResults',
486                 $recs->{count},
487         );
488
489         $feed->_create_node(
490                 $feed->{item_xpath},
491                 'http://a9.com/-/spec/opensearch/1.1/',
492                 'startIndex',
493                 $offset + 1,
494         );
495
496         $feed->_create_node(
497                 $feed->{item_xpath},
498                 'http://a9.com/-/spec/opensearch/1.1/',
499                 'itemsPerPage',
500                 $limit,
501         );
502
503         $feed->link(
504                 next =>
505                 $base . $path . "?startIndex=" . int($offset + $limit + 1) . "&count=" . $limit =>
506                 'application/opensearch+xml'
507         ) if ($offset + $limit < $recs->{count});
508
509         $feed->link(
510                 prev =>
511                 $base . $path . "?startIndex=" . int(($offset - $limit) + 1) . "&count=" . $limit =>
512                 'application/opensearch+xml'
513         ) if ($offset);
514
515         $feed->link(
516                 self =>
517                 $base . $path =>
518                 'application/opensearch+xml'
519         );
520
521
522         print "Content-type: application/xml; charset=utf-8\n\n";
523
524         print entityize($feed->toString) . "\n";
525         return Apache2::Const::OK;
526 }
527
528 sub create_record_feed {
529         my $type = shift;
530         my $records = shift;
531         my $unapi = shift;
532
533         my $cgi = new CGI;
534         my $base = $cgi->url;
535         my $host = $cgi->virtual_host || $cgi->server_name;
536
537         my $year = (gmtime())[5];
538
539         my $feed = new OpenILS::WWW::SuperCat::Feed ($type);
540         $feed->base($base);
541         $feed->unapi($unapi);
542
543         for my $rec (@$records) {
544                 my $item_tag = "tag:$host,$year:biblio-record_entry/" . $rec;
545
546                 my $xml = $supercat->request(
547                         "open-ils.supercat.record.$type.retrieve",
548                         $rec
549                 )->gather(1);
550
551                 my $node = $feed->add_item($xml);
552
553                 $node->id($item_tag);
554                 $node->link(opac => $feed->unapi . "?uri=$item_tag&format=opac");
555                 $node->link(unapi => $feed->unapi . "?uri=$item_tag");
556         }
557
558         return $feed;
559 }
560
561 sub entityize {
562         my $stuff = NFC(shift());
563         $stuff =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
564         return $stuff;
565 }
566
567 1;