]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/WWW/SuperCat.pm
slimpac. yay!
[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 NOT_FOUND :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::Utils::Cache;
17 use OpenSRF::System;
18 use OpenSRF::AppSession;
19 use XML::LibXML;
20 use XML::LibXSLT;
21
22 use Encode;
23 use Unicode::Normalize;
24 use OpenILS::Utils::Fieldmapper;
25 use OpenILS::WWW::SuperCat::Feed;
26 use OpenSRF::Utils::Logger qw/$logger/;
27
28
29 # set the bootstrap config when this module is loaded
30 my ($bootstrap, $cstore, $supercat, $actor, $parser, $search, $xslt, $cn_browse_xslt, %browse_types);
31
32 $browse_types{call_number}{xml} = sub {
33         my $tree = shift;
34
35         my $year = (gmtime())[5] + 1900;
36         my $content = '';
37
38         $content .= "<hold:volumes  xmlns:hold='http://open-ils.org/spec/holdings/v1'>";
39
40         for my $cn (@$tree) {
41                 (my $cn_class = $cn->class_name) =~ s/::/-/gso;
42                 $cn_class =~ s/Fieldmapper-//gso;
43
44                 my $cn_tag = "tag:open-ils.org,$year:$cn_class/".$cn->id;
45                 my $cn_lib = $cn->owning_lib->shortname;
46                 my $cn_label = $cn->label;
47
48                 $cn_label =~ s/\n//gos;
49                 $cn_label =~ s/'/&apos;/go;
50
51                 (my $ou_class = $cn->owning_lib->class_name) =~ s/::/-/gso;
52                 $ou_class =~ s/Fieldmapper-//gso;
53
54                 my $ou_tag = "tag:open-ils.org,$year:$ou_class/".$cn->owning_lib->id;
55                 my $ou_name = $cn->owning_lib->name;
56
57                 $ou_name =~ s/\n//gos;
58                 $ou_name =~ s/'/&apos;/go;
59
60                 (my $rec_class = $cn->record->class_name) =~ s/::/-/gso;
61                 $rec_class =~ s/Fieldmapper-//gso;
62
63                 my $rec_tag = "tag:open-ils.org,$year:$rec_class/".$cn->record->id.'/'.$cn->owning_lib->shortname;
64
65                 $content .= "<hold:volume id='$cn_tag' lib='$cn_lib' label='$cn_label'>";
66                 $content .= "<act:owning_lib xmlns:act='http://open-ils.org/spec/actors/v1' id='$ou_tag' name='$ou_name'/>";
67
68                 my $r_doc = $parser->parse_string($cn->record->marc);
69                 $r_doc->documentElement->setAttribute( id => $rec_tag );
70                 $content .= entityize($r_doc->documentElement->toString);
71
72                 $content .= "</hold:volume>";
73         }
74
75         $content .= '</hold:volumes>';
76         return ("Content-type: application/xml\n\n",$content);
77 };
78
79
80 $browse_types{call_number}{html} = sub {
81         my $tree = shift;
82         my $p = shift;
83         my $n = shift;
84
85         if (!$cn_browse_xslt) {
86                 $cn_browse_xslt = $parser->parse_file(
87                         OpenSRF::Utils::SettingsClient
88                                 ->new
89                                 ->config_value( dirs => 'xsl' ).
90                         "/CNBrowse2HTML.xsl"
91                 );
92                 $cn_browse_xslt = $xslt->parse_stylesheet( $cn_browse_xslt );
93         }
94
95         my (undef,$xml) = $browse_types{call_number}{xml}->($tree);
96
97         return (
98                 "Content-type: text/html\n\n",
99                 entityize(
100                         $cn_browse_xslt->transform(
101                                 $parser->parse_string( $xml ),
102                                 'prev' => "'$p'",
103                                 'next' => "'$n'"
104                         )->toString(1)
105                 )
106         );
107 };
108
109 sub import {
110         my $self = shift;
111         $bootstrap = shift;
112 }
113
114
115 sub child_init {
116         OpenSRF::System->bootstrap_client( config_file => $bootstrap );
117         
118         my $idl = OpenSRF::Utils::SettingsClient->new->config_value("IDL");
119         Fieldmapper->import(IDL => $idl);
120
121         $supercat = OpenSRF::AppSession->create('open-ils.supercat');
122         $cstore = OpenSRF::AppSession->create('open-ils.cstore');
123         $actor = OpenSRF::AppSession->create('open-ils.actor');
124         $search = OpenSRF::AppSession->create('open-ils.search');
125         $parser = new XML::LibXML;
126         $xslt = new XML::LibXSLT;
127
128         $cn_browse_xslt = $parser->parse_file(
129                 OpenSRF::Utils::SettingsClient
130                         ->new
131                         ->config_value( dirs => 'xsl' ).
132                 "/CNBrowse2HTML.xsl"
133         );
134
135         $cn_browse_xslt = $xslt->parse_stylesheet( $cn_browse_xslt );
136
137 }
138
139 sub oisbn {
140
141         my $apache = shift;
142         return Apache2::Const::DECLINED if (-e $apache->filename);
143
144         (my $isbn = $apache->path_info) =~ s{^.*?([^/]+)$}{$1}o;
145
146         my $list = $supercat
147                 ->request("open-ils.supercat.oisbn", $isbn)
148                 ->gather(1);
149
150         print "Content-type: application/xml; charset=utf-8\n\n";
151         print "<?xml version='1.0' encoding='UTF-8' ?>\n";
152
153         unless (exists $$list{metarecord}) {
154                 print '<idlist/>';
155                 return Apache2::Const::OK;
156         }
157
158         print "<idlist metarecord='$$list{metarecord}'>\n";
159
160         for ( keys %{ $$list{record_list} } ) {
161                 (my $o = $$list{record_list}{$_}) =~s/^(\S+).*?$/$1/o;
162                 print "  <isbn record='$_'>$o</isbn>\n"
163         }
164
165         print "</idlist>\n";
166
167         return Apache2::Const::OK;
168 }
169
170 sub unapi {
171
172         my $apache = shift;
173         return Apache2::Const::DECLINED if (-e $apache->filename);
174
175         my $cgi = new CGI;
176
177         my $add_path = 0;
178         if ( $cgi->server_software !~ m|^Apache/2.2| ) {
179                 my $rel_name = $cgi->url(-relative=>1);
180                 $add_path = 1 if ($cgi->url(-path_info=>1) !~ /$rel_name$/);
181         }
182
183         my $url = $cgi->url(-path_info=>$add_path);
184         my $root = (split 'unapi', $url)[0];
185         my $base = (split 'unapi', $url)[0] . 'unapi';
186
187
188         my $uri = $cgi->param('id') || '';
189         my $host = $cgi->virtual_host || $cgi->server_name;
190
191         my $format = $cgi->param('format');
192         my $flesh_feed = ($format =~ /-full$/o) ? 1 : 0;
193         (my $base_format = $format) =~ s/-full$//o;
194         my ($id,$type,$command,$lib) = ('','','');
195
196         if (!$format) {
197                 my $body = "Content-type: application/xml; charset=utf-8\n\n";
198         
199                 if ($uri =~ m{^tag:[^:]+:([^\/]+)/([^/]+)(?:/(.+))$}o) {
200                         $id = $2;
201                         $lib = uc($3);
202                         $type = 'record';
203                         $type = 'metarecord' if ($1 =~ /^m/o);
204
205                         my $list = $supercat
206                                 ->request("open-ils.supercat.$type.formats")
207                                 ->gather(1);
208
209                         if ($type eq 'record' or $type eq 'isbn') {
210                                 $body .= <<"                            FORMATS";
211 <formats id='$uri'>
212         <format name='opac' type='text/html'/>
213         <format name='html' type='text/html'/>
214         <format name='htmlholdings' type='text/html'/>
215         <format name='html-full' type='text/html'/>
216         <format name='htmlholdings-full' type='text/html'/>
217                                 FORMATS
218                         } elsif ($type eq 'metarecord') {
219                                 $body .= <<"                            FORMATS";
220                                 <formats id='$uri'>
221                                         <format name='opac' type='text/html'/>
222                                 FORMATS
223                         }
224
225                         for my $h (@$list) {
226                                 my ($type) = keys %$h;
227                                 $body .= "\t<format name='$type' type='application/xml'";
228
229                                 for my $part ( qw/namespace_uri docs schema_location/ ) {
230                                         $body .= " $part='$$h{$type}{$part}'"
231                                                 if ($$h{$type}{$part});
232                                 }
233                                 
234                                 $body .= "/>\n";
235
236                                 if (OpenILS::WWW::SuperCat::Feed->exists($type)) {
237                                         $body .= "\t<format name='$type-full' type='application/xml'";
238
239                                         for my $part ( qw/namespace_uri docs schema_location/ ) {
240                                                 $body .= " $part='$$h{$type}{$part}'"
241                                                         if ($$h{$type}{$part});
242                                         }
243                                 
244                                         $body .= "/>\n";
245                                 }
246                         }
247
248                         $body .= "</formats>\n";
249
250                 } else {
251                         my $list = $supercat
252                                 ->request("open-ils.supercat.record.formats")
253                                 ->gather(1);
254                                 
255                         push @$list,
256                                 @{ $supercat
257                                         ->request("open-ils.supercat.metarecord.formats")
258                                         ->gather(1);
259                                 };
260
261                         my %hash = map { ( (keys %$_)[0] => (values %$_)[0] ) } @$list;
262                         $list = [ map { { $_ => $hash{$_} } } sort keys %hash ];
263
264                         $body .= <<"                    FORMATS";
265 <formats>
266         <format name='opac' type='text/html'/>
267         <format name='html' type='text/html'/>
268         <format name='htmlholdings' type='text/html'/>
269         <format name='html-full' type='text/html'/>
270         <format name='htmlholdings-full' type='text/html'/>
271                         FORMATS
272
273
274                         for my $h (@$list) {
275                                 my ($type) = keys %$h;
276                                 $body .= "\t<format name='$type' type='application/xml'";
277
278                                 for my $part ( qw/namespace_uri docs schema_location/ ) {
279                                         $body .= " $part='$$h{$type}{$part}'"
280                                                 if ($$h{$type}{$part});
281                                 }
282                                 
283                                 $body .= "/>\n";
284
285                                 if (OpenILS::WWW::SuperCat::Feed->exists($type)) {
286                                         $body .= "\t<format name='$type-full' type='application/xml'";
287
288                                         for my $part ( qw/namespace_uri docs schema_location/ ) {
289                                                 $body .= " $part='$$h{$type}{$part}'"
290                                                         if ($$h{$type}{$part});
291                                         }
292                                 
293                                         $body .= "/>\n";
294                                 }
295                         }
296
297                         $body .= "</formats>\n";
298
299                 }
300                 print $body;
301                 return Apache2::Const::OK;
302         }
303
304         if ($uri =~ m{^tag:[^:]+:([^\/]+)/([^/]+)(?:/(.+))?}o) {
305                 $id = $2;
306                 $lib = uc($3);
307                 $type = 'record';
308                 $type = 'metarecord' if ($1 =~ /^metabib/o);
309                 $type = 'isbn' if ($1 =~ /^isbn/o);
310                 $type = 'call_number' if ($1 =~ /^call_number/o);
311                 $command = 'retrieve';
312                 $command = 'browse' if ($type eq 'call_number');
313         }
314
315         if (!$lib || $lib eq '-') {
316                 $lib = $actor->request(
317                         'open-ils.actor.org_unit_list.search' => parent_ou => undef
318                 )->gather(1)->[0]->shortname;
319         }
320
321         my $lib_object = $actor->request(
322                 'open-ils.actor.org_unit_list.search' => shortname => $lib
323         )->gather(1)->[0];
324         my $lib_id = $lib_object->id;
325
326         my $ou_types = $actor->request( 'open-ils.actor.org_types.retrieve' )->gather(1);
327         my $lib_depth = (grep { $_->id == $lib_object->ou_type } @$ou_types)[0]->depth;
328
329         if ($type eq 'call_number' and $command eq 'browse') {
330                 print "Location: $root/browse/$base_format/call_number/$lib/$id\n\n";
331                 return 302;
332         }
333
334         if ($type eq 'isbn') {
335                 my $rec = $supercat->request('open-ils.supercat.isbn.object.retrieve',$id)->gather(1);
336                 if (!@$rec) {
337                         print "Content-type: text/html; charset=utf-8\n\n";
338                         $apache->custom_response( 404, <<"                      HTML");
339                         <html>
340                                 <head>
341                                         <title>Type [$type] with id [$id] not found!</title>
342                                 </head>
343                                 <body>
344                                         <br/>
345                                         <center>Sorry, we couldn't $command a $type with the id of $id in format $format.</center>
346                                 </body>
347                         </html>
348                         HTML
349                         return 404;
350                 }
351                 $id = $rec->[0]->id;
352                 $type = 'record';
353         }
354
355         if ( !grep
356                { (keys(%$_))[0] eq $base_format }
357                @{ $supercat->request("open-ils.supercat.$type.formats")->gather(1) }
358              and !grep
359                { $_ eq $base_format }
360                qw/opac html htmlholdings/
361         ) {
362                 print "Content-type: text/html; charset=utf-8\n\n";
363                 $apache->custom_response( 406, <<"              HTML");
364                 <html>
365                         <head>
366                                 <title>Invalid format [$format] for type [$type]!</title>
367                         </head>
368                         <body>
369                                 <br/>
370                                 <center>Sorry, format $format is not valid for type $type.</center>
371                         </body>
372                 </html>
373                 HTML
374                 return 406;
375         }
376
377         if ($format eq 'opac') {
378                 print "Location: $root/../../en-US/skin/default/xml/rresult.xml?m=$id&l=$lib_id&d=$lib_depth\n\n"
379                         if ($type eq 'metarecord');
380                 print "Location: $root/../../en-US/skin/default/xml/rdetail.xml?r=$id&l=$lib_id&d=$lib_depth\n\n"
381                         if ($type eq 'record');
382                 return 302;
383         } elsif (OpenILS::WWW::SuperCat::Feed->exists($base_format)) {
384                 my $feed = create_record_feed(
385                         $type,
386                         $format => [ $id ],
387                         $base,
388                         $lib,
389                         $flesh_feed
390                 );
391
392                 if (!$feed->count) {
393                         print "Content-type: text/html; charset=utf-8\n\n";
394                         $apache->custom_response( 404, <<"                      HTML");
395                         <html>
396                                 <head>
397                                         <title>Type [$type] with id [$id] not found!</title>
398                                 </head>
399                                 <body>
400                                         <br/>
401                                         <center>Sorry, we couldn't $command a $type with the id of $id in format $format.</center>
402                                 </body>
403                         </html>
404                         HTML
405                         return 404;
406                 }
407
408                 $feed->root($root);
409                 $feed->creator($host);
410                 $feed->update_ts(gmtime_ISO8601());
411                 $feed->link( unapi => $base) if ($flesh_feed);
412
413                 print "Content-type: ". $feed->type ."; charset=utf-8\n\n";
414                 print entityize($feed->toString) . "\n";
415
416                 return Apache2::Const::OK;
417         }
418
419         my $req = $supercat->request("open-ils.supercat.$type.$format.$command",$id);
420         my $data = $req->gather(1);
421
422         if ($req->failed || !$data) {
423                 print "Content-type: text/html; charset=utf-8\n\n";
424                 $apache->custom_response( 404, <<"              HTML");
425                 <html>
426                         <head>
427                                 <title>$type $id not found!</title>
428                         </head>
429                         <body>
430                                 <br/>
431                                 <center>Sorry, we couldn't $command a $type with the id of $id in format $format.</center>
432                         </body>
433                 </html>
434                 HTML
435                 return 404;
436         }
437
438         print "Content-type: application/xml; charset=utf-8\n\n$data";
439
440         return Apache2::Const::OK;
441 }
442
443 sub supercat {
444
445         my $apache = shift;
446         return Apache2::Const::DECLINED if (-e $apache->filename);
447
448         my $cgi = new CGI;
449
450         my $add_path = 0;
451         if ( $cgi->server_software !~ m|^Apache/2.2| ) {
452                 my $rel_name = $cgi->url(-relative=>1);
453                 $add_path = 1 if ($cgi->url(-path_info=>1) !~ /$rel_name$/);
454         }
455
456         my $url = $cgi->url(-path_info=>$add_path);
457         my $root = (split 'supercat', $url)[0];
458         my $base = (split 'supercat', $url)[0] . 'supercat';
459         my $unapi = (split 'supercat', $url)[0] . 'unapi';
460
461         my $host = $cgi->virtual_host || $cgi->server_name;
462
463         my $path = $cgi->path_info;
464         my ($id,$type,$format,$command) = reverse split '/', $path;
465         my $flesh_feed = ($type =~ /-full$/o) ? 1 : 0;
466         (my $base_format = $format) =~ s/-full$//o;
467         
468         if ( $path =~ m{^/formats(?:/([^\/]+))?$}o ) {
469                 print "Content-type: application/xml; charset=utf-8\n";
470                 if ($1) {
471                         my $list = $supercat
472                                 ->request("open-ils.supercat.$1.formats")
473                                 ->gather(1);
474
475                         print "\n";
476
477                         print "<formats>
478                                    <format>
479                                      <name>opac</name>
480                                      <type>text/html</type>
481                                    </format>";
482
483                         if ($1 eq 'record' or $1 eq 'isbn') {
484                                 print "<format>
485                                      <name>htmlholdings</name>
486                                      <type>text/html</type>
487                                    </format>
488                                    <format>
489                                      <name>html</name>
490                                      <type>text/html</type>
491                                    </format>
492                                    <format>
493                                      <name>htmlholdings-full</name>
494                                      <type>text/html</type>
495                                    </format>
496                                    <format>
497                                      <name>html-full</name>
498                                      <type>text/html</type>
499                                    </format>";
500                         }
501
502                         for my $h (@$list) {
503                                 my ($type) = keys %$h;
504                                 print "<format><name>$type</name><type>application/xml</type>";
505
506                                 for my $part ( qw/namespace_uri docs schema_location/ ) {
507                                         print "<$part>$$h{$type}{$part}</$part>"
508                                                 if ($$h{$type}{$part});
509                                 }
510                                 
511                                 print '</format>';
512
513                                 if (OpenILS::WWW::SuperCat::Feed->exists($type)) {
514                                         print "<format><name>$type-full</name><type>application/xml</type>";
515
516                                         for my $part ( qw/namespace_uri docs schema_location/ ) {
517                                                 print "<$part>$$h{$type}{$part}</$part>"
518                                                         if ($$h{$type}{$part});
519                                         }
520                                 
521                                         print '</format>';
522                                 }
523
524                         }
525
526                         print "</formats>\n";
527
528                         return Apache2::Const::OK;
529                 }
530
531                 my $list = $supercat
532                         ->request("open-ils.supercat.record.formats")
533                         ->gather(1);
534                                 
535                 push @$list,
536                         @{ $supercat
537                                 ->request("open-ils.supercat.metarecord.formats")
538                                 ->gather(1);
539                         };
540
541                 my %hash = map { ( (keys %$_)[0] => (values %$_)[0] ) } @$list;
542                 $list = [ map { { $_ => $hash{$_} } } sort keys %hash ];
543
544                 print "\n<formats>
545                            <format>
546                              <name>opac</name>
547                              <type>text/html</type>
548                            </format>
549                            <format>
550                              <name>htmlholdings</name>
551                              <type>text/html</type>
552                            </format>
553                            <format>
554                              <name>html</name>
555                              <type>text/html</type>
556                            </format>
557                            <format>
558                              <name>htmlholdings-full</name>
559                              <type>text/html</type>
560                            </format>
561                            <format>
562                              <name>html-full</name>
563                              <type>text/html</type>
564                            </format>";
565
566                 for my $h (@$list) {
567                         my ($type) = keys %$h;
568                         print "<format><name>$type</name><type>application/xml</type>";
569
570                         for my $part ( qw/namespace_uri docs schema_location/ ) {
571                                 print "<$part>$$h{$type}{$part}</$part>"
572                                         if ($$h{$type}{$part});
573                         }
574                         
575                         print '</format>';
576
577                         if (OpenILS::WWW::SuperCat::Feed->exists($type)) {
578                                 print "<format><name>$type-full</name><type>application/xml</type>";
579
580                                 for my $part ( qw/namespace_uri docs schema_location/ ) {
581                                         print "<$part>$$h{$type}{$part}</$part>"
582                                                 if ($$h{$type}{$part});
583                                 }
584                                 
585                                 print '</format>';
586                         }
587
588                 }
589
590                 print "</formats>\n";
591
592
593                 return Apache2::Const::OK;
594         }
595
596         if ($format eq 'opac') {
597                 print "Location: $root/../../en-US/skin/default/xml/rresult.xml?m=$id\n\n"
598                         if ($type eq 'metarecord');
599                 print "Location: $root/../../en-US/skin/default/xml/rdetail.xml?r=$id\n\n"
600                         if ($type eq 'record');
601                 return 302;
602         } elsif (OpenILS::WWW::SuperCat::Feed->exists($base_format)) {
603                 my $feed = create_record_feed(
604                         $type,
605                         $format => [ $id ],
606                         undef, undef,
607                         $flesh_feed
608                 );
609
610                 $feed->root($root);
611                 $feed->creator($host);
612                 $feed->update_ts(gmtime_ISO8601());
613                 $feed->link( unapi => $base) if ($flesh_feed);
614
615                 print "Content-type: ". $feed->type ."; charset=utf-8\n\n";
616                 print entityize($feed->toString) . "\n";
617
618                 return Apache2::Const::OK;
619         }
620
621         my $req = $supercat->request("open-ils.supercat.$type.$format.$command",$id);
622         $req->wait_complete;
623
624         if ($req->failed) {
625                 print "Content-type: text/html; charset=utf-8\n\n";
626                 $apache->custom_response( 404, <<"              HTML");
627                 <html>
628                         <head>
629                                 <title>$type $id not found!</title>
630                         </head>
631                         <body>
632                                 <br/>
633                                 <center>Sorry, we couldn't $command a $type with the id of $id in format $format.</center>
634                         </body>
635                 </html>
636                 HTML
637                 return 404;
638         }
639
640         print "Content-type: application/xml; charset=utf-8\n\n";
641         print entityize( $parser->parse_string( $req->gather(1) )->documentElement->toString );
642
643         return Apache2::Const::OK;
644 }
645
646
647 sub bookbag_feed {
648         my $apache = shift;
649         return Apache2::Const::DECLINED if (-e $apache->filename);
650
651         my $cgi = new CGI;
652
653         my $year = (gmtime())[5] + 1900;
654         my $host = $cgi->virtual_host || $cgi->server_name;
655
656         my $add_path = 0;
657         if ( $cgi->server_software !~ m|^Apache/2.2| ) {
658                 my $rel_name = $cgi->url(-relative=>1);
659                 $add_path = 1 if ($cgi->url(-path_info=>1) !~ /$rel_name$/);
660         }
661
662         my $url = $cgi->url(-path_info=>$add_path);
663         my $root = (split 'feed', $url)[0] . '/';
664         my $base = (split 'bookbag', $url)[0] . '/bookbag';
665         my $unapi = (split 'feed', $url)[0] . '/unapi';
666
667         $root =~ s{(?<!http:)//}{/}go;
668         $base =~ s{(?<!http:)//}{/}go;
669         $unapi =~ s{(?<!http:)//}{/}go;
670
671         my $path = $cgi->path_info;
672         #warn "URL breakdown: $url -> $root -> $base -> $path -> $unapi";
673
674         my ($id,$type) = reverse split '/', $path;
675         my $flesh_feed = ($type =~ /-full$/o) ? 1 : 0;
676
677         my $bucket = $actor->request("open-ils.actor.container.public.flesh", 'biblio', $id)->gather(1);
678         return Apache2::Const::NOT_FOUND unless($bucket);
679
680         my $bucket_tag = "tag:$host,$year:record_bucket/$id";
681         if ($type eq 'opac') {
682                 print "Location: $root/../../en-US/skin/default/xml/rresult.xml?rt=list&" .
683                         join('&', map { "rl=" . $_->target_biblio_record_entry } @{ $bucket->items }) .
684                         "\n\n";
685                 return 302;
686         }
687
688         my $feed = create_record_feed(
689                 'record',
690                 $type,
691                 [ map { $_->target_biblio_record_entry } @{ $bucket->items } ],
692                 $unapi,
693                 undef,
694                 $flesh_feed
695         );
696         $feed->root($root);
697
698         $feed->title("Items in Book Bag [".$bucket->name."]");
699         $feed->creator($host);
700         $feed->update_ts(gmtime_ISO8601());
701
702         $feed->link(rss => $base . "/rss2-full/$id" => 'application/rss+xml');
703         $feed->link(alternate => $base . "/atom-full/$id" => 'application/atom+xml');
704         $feed->link(html => $base . "/html-full/$id" => 'text/html');
705         $feed->link(unapi => $unapi);
706
707         $feed->link(
708                 OPAC =>
709                 '/opac/en-US/skin/default/xml/rresult.xml?rt=list&' .
710                         join('&', map { 'rl=' . $_->target_biblio_record_entry } @{$bucket->items} ),
711                 'text/html'
712         );
713
714
715         print "Content-type: ". $feed->type ."; charset=utf-8\n\n";
716         print entityize($feed->toString) . "\n";
717
718         return Apache2::Const::OK;
719 }
720
721 sub changes_feed {
722         my $apache = shift;
723         return Apache2::Const::DECLINED if (-e $apache->filename);
724
725         my $cgi = new CGI;
726
727         my $year = (gmtime())[5] + 1900;
728         my $host = $cgi->virtual_host || $cgi->server_name;
729
730         my $add_path = 0;
731         if ( $cgi->server_software !~ m|^Apache/2.2| ) {
732                 my $rel_name = $cgi->url(-relative=>1);
733                 $add_path = 1 if ($cgi->url(-path_info=>1) !~ /$rel_name$/);
734         }
735
736         my $url = $cgi->url(-path_info=>$add_path);
737         my $root = (split 'feed', $url)[0];
738         my $base = (split 'freshmeat', $url)[0] . 'freshmeat';
739         my $unapi = (split 'feed', $url)[0] . 'unapi';
740
741         my $path = $cgi->path_info;
742         #warn "URL breakdown: $url ($rel_name) -> $root -> $base -> $path -> $unapi";
743
744         $path =~ s/^\/(?:feed\/)?freshmeat\///og;
745         
746         my ($type,$rtype,$axis,$limit,$date) = split '/', $path;
747         my $flesh_feed = ($type =~ /-full$/o) ? 1 : 0;
748         $limit ||= 10;
749
750         my $list = $supercat->request("open-ils.supercat.$rtype.record.$axis.recent", $date, $limit)->gather(1);
751
752         #if ($type eq 'opac') {
753         #       print "Location: $root/../../en-US/skin/default/xml/rresult.xml?rt=list&" .
754         #               join('&', map { "rl=" . $_ } @$list) .
755         #               "\n\n";
756         #       return 302;
757         #}
758
759         my $feed = create_record_feed( 'record', $type, $list, $unapi, undef, $flesh_feed);
760         $feed->root($root);
761
762         if ($date) {
763                 $feed->title("Up to $limit recent $rtype ${axis}s from $date forward");
764         } else {
765                 $feed->title("$limit most recent $rtype ${axis}s");
766         }
767
768         $feed->creator($host);
769         $feed->update_ts(gmtime_ISO8601());
770
771         $feed->link(rss => $base . "/rss2-full/$rtype/$axis/$limit/$date" => 'application/rss+xml');
772         $feed->link(alternate => $base . "/atom-full/$rtype/$axis/$limit/$date" => 'application/atom+xml');
773         $feed->link(html => $base . "/html-full/$rtype/$axis/$limit/$date" => 'text/html');
774         $feed->link(unapi => $unapi);
775
776         $feed->link(
777                 OPAC =>
778                 '/opac/en-US/skin/default/xml/rresult.xml?rt=list&' .
779                         join('&', map { 'rl=' . $_} @$list ),
780                 'text/html'
781         );
782
783
784         print "Content-type: ". $feed->type ."; charset=utf-8\n\n";
785         print entityize($feed->toString) . "\n";
786
787         return Apache2::Const::OK;
788 }
789
790 sub opensearch_osd {
791         my $version = shift;
792         my $lib = shift;
793         my $class = shift;
794         my $base = shift;
795
796         if ($version eq '1.0') {
797                 print <<OSD;
798 Content-type: application/opensearchdescription+xml; charset=utf-8
799
800 <?xml version="1.0" encoding="UTF-8"?>
801 <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearchdescription/1.0/">
802   <Url>$base/1.0/$lib/-/$class/?searchTerms={searchTerms}&amp;startPage={startPage}&amp;startIndex={startIndex}&amp;count={count}</Url>
803   <Format>http://a9.com/-/spec/opensearchrss/1.0/</Format>
804   <ShortName>$lib</ShortName>
805   <LongName>Search $lib</LongName>
806   <Description>Search the $lib OPAC by $class.</Description>
807   <Tags>$lib book library</Tags>
808   <SampleSearch>harry+potter</SampleSearch>
809   <Developer>Mike Rylander for GPLS/PINES</Developer>
810   <Contact>feedback\@open-ils.org</Contact>
811   <SyndicationRight>open</SyndicationRight>
812   <AdultContent>false</AdultContent>
813 </OpenSearchDescription>
814 OSD
815         } else {
816                 print <<OSD;
817 Content-type: application/opensearchdescription+xml; charset=utf-8
818
819 <?xml version="1.0" encoding="UTF-8"?>
820 <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">
821   <ShortName>$lib</ShortName>
822   <Description>Search the $lib OPAC by $class.</Description>
823   <Tags>$lib book library</Tags>
824   <Url type="application/rss+xml"
825        template="$base/1.1/$lib/rss2-full/$class/?searchTerms={searchTerms}&amp;startPage={startPage?}&amp;startIndex={startIndex?}&amp;count={count?}&amp;searchLang={language?}"/>
826   <Url type="application/atom+xml"
827        template="$base/1.1/$lib/atom-full/$class/?searchTerms={searchTerms}&amp;startPage={startPage?}&amp;startIndex={startIndex?}&amp;count={count?}&amp;searchLang={language?}"/>
828   <Url type="application/x-mods3+xml"
829        template="$base/1.1/$lib/mods3/$class/?searchTerms={searchTerms}&amp;startPage={startPage?}&amp;startIndex={startIndex?}&amp;count={count?}&amp;searchLang={language?}"/>
830   <Url type="application/x-mods+xml"
831        template="$base/1.1/$lib/mods/$class/?searchTerms={searchTerms}&amp;startPage={startPage?}&amp;startIndex={startIndex?}&amp;count={count?}&amp;searchLang={language?}"/>
832   <Url type="application/x-marcxml+xml"
833        template="$base/1.1/$lib/marcxml/$class/?searchTerms={searchTerms}&amp;startPage={startPage?}&amp;startIndex={startIndex?}&amp;count={count?}&amp;searchLang={language?}"/>
834   <LongName>Search $lib</LongName>
835   <Query role="example" searchTerms="harry+potter" />
836   <Developer>Mike Rylander for GPLS/PINES</Developer>
837   <Contact>feedback\@open-ils.org</Contact>
838   <SyndicationRight>open</SyndicationRight>
839   <AdultContent>false</AdultContent>
840   <Language>en-US</Language>
841   <OutputEncoding>UTF-8</OutputEncoding>
842   <InputEncoding>UTF-8</InputEncoding>
843 </OpenSearchDescription>
844 OSD
845         }
846
847         return Apache2::Const::OK;
848 }
849
850 sub opensearch_feed {
851         my $apache = shift;
852         return Apache2::Const::DECLINED if (-e $apache->filename);
853
854         my $cgi = new CGI;
855         my $year = (gmtime())[5] + 1900;
856
857         my $host = $cgi->virtual_host || $cgi->server_name;
858
859         my $add_path = 0;
860         if ( $cgi->server_software !~ m|^Apache/2.2| ) {
861                 my $rel_name = $cgi->url(-relative=>1);
862                 $add_path = 1 if ($cgi->url(-path_info=>1) !~ /$rel_name$/);
863         }
864
865         my $url = $cgi->url(-path_info=>$add_path);
866         my $root = (split 'opensearch', $url)[0];
867         my $base = (split 'opensearch', $url)[0] . 'opensearch';
868         my $unapi = (split 'opensearch', $url)[0] . 'unapi';
869
870         my $path = $cgi->path_info;
871         #warn "URL breakdown: $url ($rel_name) -> $root -> $base -> $path -> $unapi";
872
873         if ($path =~ m{^/?(1\.\d{1})/(?:([^/]+)/)?([^/]+)/osd.xml}o) {
874                 
875                 my $version = $1;
876                 my $lib = uc($2);
877                 my $class = $3;
878
879                 if (!$lib || $lib eq '-') {
880                         $lib = $actor->request(
881                                 'open-ils.actor.org_unit_list.search' => parent_ou => undef
882                         )->gather(1)->[0]->shortname;
883                 }
884
885                 if ($class eq '-') {
886                         $class = 'keyword';
887                 }
888
889                 return opensearch_osd($version, $lib, $class, $base);
890         }
891
892
893         my $page = $cgi->param('startPage') || 1;
894         my $offset = $cgi->param('startIndex') || 1;
895         my $limit = $cgi->param('count') || 10;
896
897         $page = 1 if ($page !~ /^\d+$/);
898         $offset = 1 if ($offset !~ /^\d+$/);
899         $limit = 10 if ($limit !~ /^\d+$/); $limit = 25 if ($limit > 25);
900
901         if ($page > 1) {
902                 $offset = ($page - 1) * $limit;
903         } else {
904                 $offset -= 1;
905         }
906
907         my ($version,$org,$type,$class,$terms,$sort,$sortdir,$lang);
908         (undef,$version,$org,$type,$class,$terms,$sort,$sortdir,$lang) = split '/', $path;
909
910         $lang = $cgi->param('searchLang') if $cgi->param('searchLang');
911         $sort = $cgi->param('searchSort') if $cgi->param('searchSort');
912         $sortdir = $cgi->param('searchSortDir') if $cgi->param('searchSortDir');
913         $terms .= " " . $cgi->param('searchTerms') if $cgi->param('searchTerms');
914
915         $class = $cgi->param('searchClass') if $cgi->param('searchClass');
916         $class ||= '-';
917
918         $type = $cgi->param('responseType') if $cgi->param('responseType');
919         $type ||= '-';
920
921         $org = $cgi->param('searchOrg') if $cgi->param('searchOrg');
922         $org ||= '-';
923
924
925         my $kwt = $cgi->param('kw');
926         my $tit = $cgi->param('ti');
927         my $aut = $cgi->param('au');
928         my $sut = $cgi->param('su');
929         my $set = $cgi->param('se');
930
931         $terms .= " keyword: $kwt" if ($kwt);
932         $terms .= " title: $tit" if ($tit);
933         $terms .= " author: $aut" if ($aut);
934         $terms .= " subject: $sut" if ($sut);
935         $terms .= " series: $set" if ($set);
936
937         if ($version eq '1.0') {
938                 $type = 'rss2';
939         } elsif ($type eq '-') {
940                 $type = 'atom';
941         }
942         my $flesh_feed = ($type =~ /-full$/o) ? 1 : 0;
943
944         $terms = decode_utf8($terms);
945         $terms =~ s/\+/ /go;
946         $terms =~ s/'//go;
947         my $term_copy = $terms;
948
949         my $complex_terms = 0;
950         if ($terms eq 'help') {
951                 print $cgi->header(-type => 'text/html');
952                 print <<"               HTML";
953                         <html>
954                          <head>
955                           <title>just type something!</title>
956                          </head>
957                          <body>
958                           <p>You are in a maze of dark, twisty stacks, all alike.</p>
959                          </body>
960                         </html>
961                 HTML
962                 return Apache2::Const::OK;
963         }
964
965         my $cache_key = '';
966         my $searches = {};
967         while ($term_copy =~ s/((?:keyword|title|author|subject|series|site|dir|sort|lang):[^:]+)$//so) {
968                 my ($c,$t) = split ':' => $1;
969                 if ($c eq 'site') {
970                         $org = $t;
971                         $org =~ s/^\s*//o;
972                         $org =~ s/\s*$//o;
973                 } elsif ($c eq 'sort') {
974                         ($sort = lc($t)) =~ s/^\s*(\w+)\s*$/$1/go;
975                 } elsif ($c eq 'dir') {
976                         ($sortdir = lc($t)) =~ s/^\s*(\w+)\s*$/$1/go;
977                 } elsif ($c eq 'lang') {
978                         ($lang = lc($t)) =~ s/^\s*(\w+)\s*$/$1/go;
979                 } else {
980                         $$searches{$c}{term} .= ' '.$t;
981                         $cache_key .= $c . $t;
982                         $complex_terms = 1;
983                 }
984         }
985
986         if ($term_copy) {
987                 no warnings;
988                 $class = 'keyword' if ($class eq '-');
989                 $$searches{$class}{term} .= " $term_copy";
990                 $cache_key .= $class . $term_copy;
991         }
992
993         my $org_unit;
994         if ($org eq '-') {
995                 $org_unit = $actor->request(
996                         'open-ils.actor.org_unit_list.search' => parent_ou => undef
997                 )->gather(1);
998         } else {
999                 $org_unit = $actor->request(
1000                         'open-ils.actor.org_unit_list.search' => shortname => uc($org)
1001                 )->gather(1);
1002         }
1003
1004         { no warnings; $cache_key .= $org.$sort.$sortdir.$lang; }
1005
1006         my $rs_name = $cgi->cookie('os_session');
1007         my $cached_res = OpenSRF::Utils::Cache->new->get_cache( "os_session:$rs_name" ) if ($rs_name);
1008
1009         my $recs;
1010         if (!($recs = $$cached_res{os_results}{$cache_key})) {
1011                 $rs_name = $cgi->remote_host . '::' . rand(time);
1012                 $recs = $search->request(
1013                         'open-ils.search.biblio.multiclass' => {
1014                                 searches        => $searches,
1015                                 org_unit        => $org_unit->[0]->id,
1016                                 offset          => 0,
1017                                 limit           => 5000,
1018                                 ($sort ?    ( 'sort'     => $sort    ) : ()),
1019                                 ($sortdir ? ( 'sort_dir' => $sortdir ) : ($sort ? (sort_dir => 'asc') : (sort_dir => 'desc') )),
1020                                 ($lang ?    ( 'language' => $lang    ) : ()),
1021                         }
1022                 )->gather(1);
1023                 try {
1024                         $$cached_res{os_results}{$cache_key} = $recs;
1025                         OpenSRF::Utils::Cache->new->put_cache( "os_session:$rs_name", $cached_res, 1800 );
1026                 } catch Error with {
1027                         warn "supercat unable to store IDs in memcache server\n";
1028                         $logger->error("supercat unable to store IDs in memcache server");
1029                 };
1030         }
1031
1032         my $feed = create_record_feed(
1033                 'record',
1034                 $type,
1035                 [ map { $_->[0] } @{$recs->{ids}}[$offset .. $offset + $limit - 1] ],
1036                 $unapi,
1037                 $org,
1038                 $flesh_feed
1039         );
1040         $feed->root($root);
1041         $feed->lib($org);
1042         $feed->search($terms);
1043         $feed->class($class);
1044
1045         if ($complex_terms) {
1046                 $feed->title("Search results for [$terms] at ".$org_unit->[0]->name);
1047         } else {
1048                 $feed->title("Search results for [$class => $terms] at ".$org_unit->[0]->name);
1049         }
1050
1051         $feed->creator($host);
1052         $feed->update_ts(gmtime_ISO8601());
1053
1054         $feed->_create_node(
1055                 $feed->{item_xpath},
1056                 'http://a9.com/-/spec/opensearch/1.1/',
1057                 'totalResults',
1058                 $recs->{count},
1059         );
1060
1061         $feed->_create_node(
1062                 $feed->{item_xpath},
1063                 'http://a9.com/-/spec/opensearch/1.1/',
1064                 'startIndex',
1065                 $offset + 1,
1066         );
1067
1068         $feed->_create_node(
1069                 $feed->{item_xpath},
1070                 'http://a9.com/-/spec/opensearch/1.1/',
1071                 'itemsPerPage',
1072                 $limit,
1073         );
1074
1075         $feed->link(
1076                 next =>
1077                 $base . "/$version/$org/$type/$class?searchTerms=$terms&startIndex=" . int($offset + $limit + 1) . "&count=" . $limit =>
1078                 'application/opensearch+xml'
1079         ) if ($offset + $limit < $recs->{count});
1080
1081         $feed->link(
1082                 previous =>
1083                 $base . "/$version/$org/$type/$class?searchTerms=$terms&startIndex=" . int(($offset - $limit) + 1) . "&count=" . $limit =>
1084                 'application/opensearch+xml'
1085         ) if ($offset);
1086
1087         $feed->link(
1088                 self =>
1089                 $base .  "/$version/$org/$type/$class?searchTerms=$terms" =>
1090                 'application/opensearch+xml'
1091         );
1092
1093         $feed->link(
1094                 rss =>
1095                 $base .  "/$version/$org/rss2-full/$class?searchTerms=$terms" =>
1096                 'application/rss+xml'
1097         );
1098
1099         $feed->link(
1100                 alternate =>
1101                 $base .  "/$version/$org/atom-full/$class?searchTerms=$terms" =>
1102                 'application/atom+xml'
1103         );
1104
1105         $feed->link(
1106                 'html' =>
1107                 $base .  "/$version/$org/html/$class?searchTerms=$terms" =>
1108                 'text/html'
1109         );
1110
1111         $feed->link(
1112                 'html-full' =>
1113                 $base .  "/$version/$org/html-full/$class?searchTerms=$terms" =>
1114                 'text/html'
1115         );
1116
1117         $feed->link( 'unapi-server' => $unapi);
1118
1119 #       $feed->link(
1120 #               opac =>
1121 #               $root . "../$lang/skin/default/xml/rresult.xml?rt=list&" .
1122 #                       join('&', map { 'rl=' . $_->[0] } grep { ref $_ && defined $_->[0] } @{$recs->{ids}} ),
1123 #               'text/html'
1124 #       );
1125
1126         print $cgi->header(
1127                 -type           => $feed->type,
1128                 -charset        => 'UTF-8',
1129                 -cookie         => $cgi->cookie( -name => 'os_session', -value => $rs_name, -expires => '+30m' ),
1130         );
1131
1132         print entityize($feed->toString) . "\n";
1133
1134         return Apache2::Const::OK;
1135 }
1136
1137 sub create_record_feed {
1138         my $search = shift;
1139         my $type = shift;
1140         my $records = shift;
1141         my $unapi = shift;
1142
1143         my $lib = uc(shift()) || '-';
1144         my $flesh = shift;
1145         $flesh = 1 if (!defined($flesh));
1146
1147         my $cgi = new CGI;
1148         my $base = $cgi->url;
1149         my $host = $cgi->virtual_host || $cgi->server_name;
1150
1151         my $year = (gmtime())[5] + 1900;
1152
1153         my $flesh_feed = ($type =~ s/-full$//o) ? 1 : 0;
1154
1155         my $feed = new OpenILS::WWW::SuperCat::Feed ($type);
1156         $feed->base($base) if ($flesh);
1157         $feed->unapi($unapi) if ($flesh);
1158
1159         $type = 'atom' if ($type eq 'html');
1160         $type = 'marcxml' if ($type eq 'htmlholdings');
1161
1162         #$records = $supercat->request( "open-ils.supercat.record.object.retrieve", $records )->gather(1);
1163
1164         my $count = 0;
1165         for my $record (@$records) {
1166                 next unless($record);
1167
1168                 #my $rec = $record->id;
1169                 my $rec = $record;
1170
1171                 my $item_tag = "tag:$host,$year:biblio-record_entry/$rec/$lib";
1172                 $item_tag = "tag:$host,$year:isbn/$rec/$lib" if ($search eq 'isbn');
1173
1174                 my $xml = $supercat->request(
1175                         "open-ils.supercat.$search.$type.retrieve",
1176                         $rec
1177                 )->gather(1);
1178                 next unless $xml;
1179
1180                 my $node = $feed->add_item($xml);
1181                 next unless $node;
1182
1183                 if ($lib && $type eq 'marcxml' &&  $flesh) {
1184                         $xml = $supercat->request( "open-ils.supercat.$search.holdings_xml.retrieve", $rec, $lib )->gather(1);
1185                         $node->add_holdings($xml);
1186                 }
1187
1188                 $node->id($item_tag) if ($flesh);
1189                 #$node->update_ts(clense_ISO8601($record->edit_date));
1190                 $node->link(alternate => $feed->unapi . "?id=$item_tag&format=htmlholdings-full" => 'text/html') if ($flesh);
1191                 $node->link(opac => $feed->unapi . "?id=$item_tag&format=opac") if ($flesh);
1192                 $node->link(unapi => $feed->unapi . "?id=$item_tag") if ($flesh);
1193                 $node->link('unapi-id' => $item_tag) if ($flesh);
1194         }
1195
1196         return $feed;
1197 }
1198
1199 sub entityize {
1200         my $stuff = NFC(shift());
1201         $stuff =~ s/&(?!\S+;)/&amp;/gso;
1202         $stuff =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
1203         return $stuff;
1204 }
1205
1206 sub string_browse {
1207         my $apache = shift;
1208         return Apache2::Const::DECLINED if (-e $apache->filename);
1209
1210         my $cgi = new CGI;
1211         my $year = (gmtime())[5] + 1900;
1212
1213         my $host = $cgi->virtual_host || $cgi->server_name;
1214
1215         my $add_path = 0;
1216         if ( $cgi->server_software !~ m|^Apache/2.2| ) {
1217                 my $rel_name = $cgi->url(-relative=>1);
1218                 $add_path = 1 if ($cgi->url(-path_info=>1) !~ /$rel_name$/);
1219         }
1220
1221         my $url = $cgi->url(-path_info=>$add_path);
1222         my $root = (split 'browse', $url)[0];
1223         my $base = (split 'browse', $url)[0] . 'browse';
1224         my $unapi = (split 'browse', $url)[0] . 'unapi';
1225
1226         my $path = $cgi->path_info;
1227         $path =~ s/^\///og;
1228
1229         my ($format,$axis,$site,$string,$page,$page_size) = split '/', $path;
1230         #warn " >>> $format -> $axis -> $site -> $string -> $page -> $page_size ";
1231
1232         $site ||= $cgi->param('searchOrg');
1233         $page ||= $cgi->param('startPage') || 0;
1234         $page_size ||= $cgi->param('count') || 9;
1235
1236         $page = 0 if ($page !~ /^-?\d+$/);
1237
1238         my $prev = join('/', $base,$format,$axis,$site,$string,$page - 1,$page_size);
1239         my $next = join('/', $base,$format,$axis,$site,$string,$page + 1,$page_size);
1240
1241         unless ($string and $axis and grep { $axis eq $_ } keys %browse_types) {
1242                 warn "something's wrong...";
1243                 warn " >>> $format -> $axis -> $site -> $string -> $page -> $page_size ";
1244                 return undef;
1245         }
1246
1247         $string = decode_utf8($string);
1248         $string =~ s/\+/ /go;
1249         $string =~ s/'//go;
1250
1251         my $tree = $supercat->request(
1252                 "open-ils.supercat.$axis.browse",
1253                 $string,
1254                 $site,
1255                 $page_size,
1256                 $page
1257         )->gather(1);
1258
1259         my ($header,$content) = $browse_types{$axis}{$format}->($tree,$prev,$next);
1260         print $header.$content;
1261         return Apache2::Const::OK;
1262 }
1263
1264 1;