]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/WWW/SuperCat.pm
improving ISBN based unapi stuff
[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 = $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 = $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) {
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                 $lib = uc($lib);
331                 print "Location: $root/browse/$base_format/call_number/$lib/$id\n\n";
332                 return 302;
333         }
334
335         if ($type eq 'isbn') {
336                 my $rec = $supercat->request('open-ils.supercat.isbn.object.retrieve',$id)->gather(1);
337                 if (!@$rec) {
338                         print "Content-type: text/html; charset=utf-8\n\n";
339                         $apache->custom_response( 404, <<"                      HTML");
340                         <html>
341                                 <head>
342                                         <title>Type [$type] with id [$id] not found!</title>
343                                 </head>
344                                 <body>
345                                         <br/>
346                                         <center>Sorry, we couldn't $command a $type with the id of $id in format $format.</center>
347                                 </body>
348                         </html>
349                         HTML
350                         return 404;
351                 }
352                 $id = $rec->[0]->id;
353                 $type = 'record';
354         }
355
356         if ( !grep
357                { (keys(%$_))[0] eq $base_format }
358                @{ $supercat->request("open-ils.supercat.$type.formats")->gather(1) }
359              and !grep
360                { $_ eq $base_format }
361                qw/opac html htmlholdings/
362         ) {
363                 print "Content-type: text/html; charset=utf-8\n\n";
364                 $apache->custom_response( 406, <<"              HTML");
365                 <html>
366                         <head>
367                                 <title>Invalid format [$format] for type [$type]!</title>
368                         </head>
369                         <body>
370                                 <br/>
371                                 <center>Sorry, format $format is not valid for type $type.</center>
372                         </body>
373                 </html>
374                 HTML
375                 return 406;
376         }
377
378         if ($format eq 'opac') {
379                 print "Location: $root/../../en-US/skin/default/xml/rresult.xml?m=$id&l=$lib_id&d=$lib_depth\n\n"
380                         if ($type eq 'metarecord');
381                 print "Location: $root/../../en-US/skin/default/xml/rdetail.xml?r=$id&l=$lib_id&d=$lib_depth\n\n"
382                         if ($type eq 'record');
383                 return 302;
384         } elsif (OpenILS::WWW::SuperCat::Feed->exists($base_format)) {
385                 my $feed = create_record_feed(
386                         $type,
387                         $format => [ $id ],
388                         $base,
389                         $lib,
390                         $flesh_feed
391                 );
392
393                 if (!$feed->count) {
394                         print "Content-type: text/html; charset=utf-8\n\n";
395                         $apache->custom_response( 404, <<"                      HTML");
396                         <html>
397                                 <head>
398                                         <title>Type [$type] with id [$id] not found!</title>
399                                 </head>
400                                 <body>
401                                         <br/>
402                                         <center>Sorry, we couldn't $command a $type with the id of $id in format $format.</center>
403                                 </body>
404                         </html>
405                         HTML
406                         return 404;
407                 }
408
409                 $feed->root($root);
410                 $feed->creator($host);
411                 $feed->update_ts(gmtime_ISO8601());
412                 $feed->link( unapi => $base) if ($flesh_feed);
413
414                 print "Content-type: ". $feed->type ."; charset=utf-8\n\n";
415                 print entityize($feed->toString) . "\n";
416
417                 return Apache2::Const::OK;
418         }
419
420         my $req = $supercat->request("open-ils.supercat.$type.$format.$command",$id);
421         my $data = $req->gather(1);
422
423         if ($req->failed || !$data) {
424                 print "Content-type: text/html; charset=utf-8\n\n";
425                 $apache->custom_response( 404, <<"              HTML");
426                 <html>
427                         <head>
428                                 <title>$type $id not found!</title>
429                         </head>
430                         <body>
431                                 <br/>
432                                 <center>Sorry, we couldn't $command a $type with the id of $id in format $format.</center>
433                         </body>
434                 </html>
435                 HTML
436                 return 404;
437         }
438
439         print "Content-type: application/xml; charset=utf-8\n\n$data";
440
441         return Apache2::Const::OK;
442 }
443
444 sub supercat {
445
446         my $apache = shift;
447         return Apache2::Const::DECLINED if (-e $apache->filename);
448
449         my $cgi = new CGI;
450
451         my $add_path = 0;
452         if ( $cgi->server_software !~ m|^Apache/2.2| ) {
453                 my $rel_name = $cgi->url(-relative=>1);
454                 $add_path = 1 if ($cgi->url(-path_info=>1) !~ /$rel_name$/);
455         }
456
457         my $url = $cgi->url(-path_info=>$add_path);
458         my $root = (split 'supercat', $url)[0];
459         my $base = (split 'supercat', $url)[0] . 'supercat';
460         my $unapi = (split 'supercat', $url)[0] . 'unapi';
461
462         my $host = $cgi->virtual_host || $cgi->server_name;
463
464         my $path = $cgi->path_info;
465         my ($id,$type,$format,$command) = reverse split '/', $path;
466         my $flesh_feed = ($type =~ /-full$/o) ? 1 : 0;
467         (my $base_format = $format) =~ s/-full$//o;
468         
469         if ( $path =~ m{^/formats(?:/([^\/]+))?$}o ) {
470                 print "Content-type: application/xml; charset=utf-8\n";
471                 if ($1) {
472                         my $list = $supercat
473                                 ->request("open-ils.supercat.$1.formats")
474                                 ->gather(1);
475
476                         print "\n";
477
478                         print "<formats>
479                                    <format>
480                                      <name>opac</name>
481                                      <type>text/html</type>
482                                    </format>";
483
484                         if ($1 eq 'record' or $1 eq 'isbn') {
485                                 print "<format>
486                                      <name>htmlholdings</name>
487                                      <type>text/html</type>
488                                    </format>
489                                    <format>
490                                      <name>html</name>
491                                      <type>text/html</type>
492                                    </format>
493                                    <format>
494                                      <name>htmlholdings-full</name>
495                                      <type>text/html</type>
496                                    </format>
497                                    <format>
498                                      <name>html-full</name>
499                                      <type>text/html</type>
500                                    </format>";
501                         }
502
503                         for my $h (@$list) {
504                                 my ($type) = keys %$h;
505                                 print "<format><name>$type</name><type>application/xml</type>";
506
507                                 for my $part ( qw/namespace_uri docs schema_location/ ) {
508                                         print "<$part>$$h{$type}{$part}</$part>"
509                                                 if ($$h{$type}{$part});
510                                 }
511                                 
512                                 print '</format>';
513
514                                 if (OpenILS::WWW::SuperCat::Feed->exists($type)) {
515                                         print "<format><name>$type-full</name><type>application/xml</type>";
516
517                                         for my $part ( qw/namespace_uri docs schema_location/ ) {
518                                                 print "<$part>$$h{$type}{$part}</$part>"
519                                                         if ($$h{$type}{$part});
520                                         }
521                                 
522                                         print '</format>';
523                                 }
524
525                         }
526
527                         print "</formats>\n";
528
529                         return Apache2::Const::OK;
530                 }
531
532                 my $list = $supercat
533                         ->request("open-ils.supercat.record.formats")
534                         ->gather(1);
535                                 
536                 push @$list,
537                         @{ $supercat
538                                 ->request("open-ils.supercat.metarecord.formats")
539                                 ->gather(1);
540                         };
541
542                 my %hash = map { ( (keys %$_)[0] => (values %$_)[0] ) } @$list;
543                 $list = [ map { { $_ => $hash{$_} } } sort keys %hash ];
544
545                 print "\n<formats>
546                            <format>
547                              <name>opac</name>
548                              <type>text/html</type>
549                            </format>
550                            <format>
551                              <name>htmlholdings</name>
552                              <type>text/html</type>
553                            </format>
554                            <format>
555                              <name>html</name>
556                              <type>text/html</type>
557                            </format>
558                            <format>
559                              <name>htmlholdings-full</name>
560                              <type>text/html</type>
561                            </format>
562                            <format>
563                              <name>html-full</name>
564                              <type>text/html</type>
565                            </format>";
566
567                 for my $h (@$list) {
568                         my ($type) = keys %$h;
569                         print "<format><name>$type</name><type>application/xml</type>";
570
571                         for my $part ( qw/namespace_uri docs schema_location/ ) {
572                                 print "<$part>$$h{$type}{$part}</$part>"
573                                         if ($$h{$type}{$part});
574                         }
575                         
576                         print '</format>';
577
578                         if (OpenILS::WWW::SuperCat::Feed->exists($type)) {
579                                 print "<format><name>$type-full</name><type>application/xml</type>";
580
581                                 for my $part ( qw/namespace_uri docs schema_location/ ) {
582                                         print "<$part>$$h{$type}{$part}</$part>"
583                                                 if ($$h{$type}{$part});
584                                 }
585                                 
586                                 print '</format>';
587                         }
588
589                 }
590
591                 print "</formats>\n";
592
593
594                 return Apache2::Const::OK;
595         }
596
597         if ($format eq 'opac') {
598                 print "Location: $root/../../en-US/skin/default/xml/rresult.xml?m=$id\n\n"
599                         if ($type eq 'metarecord');
600                 print "Location: $root/../../en-US/skin/default/xml/rdetail.xml?r=$id\n\n"
601                         if ($type eq 'record');
602                 return 302;
603         } elsif (OpenILS::WWW::SuperCat::Feed->exists($base_format)) {
604                 my $feed = create_record_feed(
605                         $type,
606                         $format => [ $id ],
607                         undef, undef,
608                         $flesh_feed
609                 );
610
611                 $feed->root($root);
612                 $feed->creator($host);
613                 $feed->update_ts(gmtime_ISO8601());
614                 $feed->link( unapi => $base) if ($flesh_feed);
615
616                 print "Content-type: ". $feed->type ."; charset=utf-8\n\n";
617                 print entityize($feed->toString) . "\n";
618
619                 return Apache2::Const::OK;
620         }
621
622         my $req = $supercat->request("open-ils.supercat.$type.$format.$command",$id);
623         $req->wait_complete;
624
625         if ($req->failed) {
626                 print "Content-type: text/html; charset=utf-8\n\n";
627                 $apache->custom_response( 404, <<"              HTML");
628                 <html>
629                         <head>
630                                 <title>$type $id not found!</title>
631                         </head>
632                         <body>
633                                 <br/>
634                                 <center>Sorry, we couldn't $command a $type with the id of $id in format $format.</center>
635                         </body>
636                 </html>
637                 HTML
638                 return 404;
639         }
640
641         print "Content-type: application/xml; charset=utf-8\n\n";
642         print entityize( $parser->parse_string( $req->gather(1) )->documentElement->toString );
643
644         return Apache2::Const::OK;
645 }
646
647
648 sub bookbag_feed {
649         my $apache = shift;
650         return Apache2::Const::DECLINED if (-e $apache->filename);
651
652         my $cgi = new CGI;
653
654         my $year = (gmtime())[5] + 1900;
655         my $host = $cgi->virtual_host || $cgi->server_name;
656
657         my $add_path = 0;
658         if ( $cgi->server_software !~ m|^Apache/2.2| ) {
659                 my $rel_name = $cgi->url(-relative=>1);
660                 $add_path = 1 if ($cgi->url(-path_info=>1) !~ /$rel_name$/);
661         }
662
663         my $url = $cgi->url(-path_info=>$add_path);
664         my $root = (split 'feed', $url)[0];
665         my $base = (split 'bookbag', $url)[0] . 'bookbag';
666         my $unapi = (split 'feed', $url)[0] . 'unapi';
667
668
669         my $path = $cgi->path_info;
670         #warn "URL breakdown: $url -> $root -> $base -> $path -> $unapi";
671
672         my ($id,$type) = reverse split '/', $path;
673         my $flesh_feed = ($type =~ /-full$/o) ? 1 : 0;
674
675         my $bucket = $actor->request("open-ils.actor.container.public.flesh", 'biblio', $id)->gather(1);
676         return Apache2::Const::NOT_FOUND unless($bucket);
677
678         my $bucket_tag = "tag:$host,$year:record_bucket/$id";
679         if ($type eq 'opac') {
680                 print "Location: $root/../../en-US/skin/default/xml/rresult.xml?rt=list&" .
681                         join('&', map { "rl=" . $_->target_biblio_record_entry } @{ $bucket->items }) .
682                         "\n\n";
683                 return 302;
684         }
685
686         my $feed = create_record_feed(
687                 'record',
688                 $type,
689                 [ map { $_->target_biblio_record_entry } @{ $bucket->items } ],
690                 $unapi,
691                 undef,
692                 $flesh_feed
693         );
694         $feed->root($root);
695
696         $feed->title("Items in Book Bag [".$bucket->name."]");
697         $feed->creator($host);
698         $feed->update_ts(gmtime_ISO8601());
699
700         $feed->link(rss => $base . "/rss2/$id" => 'application/rss+xml');
701         $feed->link(alternate => $base . "/atom/$id" => 'application/atom+xml');
702         $feed->link(html => $base . "/html/$id" => 'text/html');
703         $feed->link(unapi => $unapi);
704
705         $feed->link(
706                 OPAC =>
707                 '/opac/en-US/skin/default/xml/rresult.xml?rt=list&' .
708                         join('&', map { 'rl=' . $_->target_biblio_record_entry } @{$bucket->items} ),
709                 'text/html'
710         );
711
712
713         print "Content-type: ". $feed->type ."; charset=utf-8\n\n";
714         print entityize($feed->toString) . "\n";
715
716         return Apache2::Const::OK;
717 }
718
719 sub changes_feed {
720         my $apache = shift;
721         return Apache2::Const::DECLINED if (-e $apache->filename);
722
723         my $cgi = new CGI;
724
725         my $year = (gmtime())[5] + 1900;
726         my $host = $cgi->virtual_host || $cgi->server_name;
727
728         my $add_path = 0;
729         if ( $cgi->server_software !~ m|^Apache/2.2| ) {
730                 my $rel_name = $cgi->url(-relative=>1);
731                 $add_path = 1 if ($cgi->url(-path_info=>1) !~ /$rel_name$/);
732         }
733
734         my $url = $cgi->url(-path_info=>$add_path);
735         my $root = (split 'feed', $url)[0];
736         my $base = (split 'freshmeat', $url)[0] . 'freshmeat';
737         my $unapi = (split 'feed', $url)[0] . 'unapi';
738
739         my $path = $cgi->path_info;
740         #warn "URL breakdown: $url ($rel_name) -> $root -> $base -> $path -> $unapi";
741
742         $path =~ s/^\/(?:feed\/)?freshmeat\///og;
743         
744         my ($type,$rtype,$axis,$limit,$date) = split '/', $path;
745         my $flesh_feed = ($type =~ /-full$/o) ? 1 : 0;
746         $limit ||= 10;
747
748         my $list = $supercat->request("open-ils.supercat.$rtype.record.$axis.recent", $date, $limit)->gather(1);
749
750         #if ($type eq 'opac') {
751         #       print "Location: $root/../../en-US/skin/default/xml/rresult.xml?rt=list&" .
752         #               join('&', map { "rl=" . $_ } @$list) .
753         #               "\n\n";
754         #       return 302;
755         #}
756
757         my $feed = create_record_feed( 'record', $type, $list, $unapi, undef, $flesh_feed);
758         $feed->root($root);
759
760         if ($date) {
761                 $feed->title("Up to $limit recent $rtype ${axis}s from $date forward");
762         } else {
763                 $feed->title("$limit most recent $rtype ${axis}s");
764         }
765
766         $feed->creator($host);
767         $feed->update_ts(gmtime_ISO8601());
768
769         $feed->link(rss => $base . "/rss2/$rtype/$axis/$limit/$date" => 'application/rss+xml');
770         $feed->link(alternate => $base . "/atom/$rtype/$axis/$limit/$date" => 'application/atom+xml');
771         $feed->link(html => $base . "/html/$rtype/$axis/$limit/$date" => 'text/html');
772         $feed->link(unapi => $unapi);
773
774         $feed->link(
775                 OPAC =>
776                 '/opac/en-US/skin/default/xml/rresult.xml?rt=list&' .
777                         join('&', map { 'rl=' . $_} @$list ),
778                 'text/html'
779         );
780
781
782         print "Content-type: ". $feed->type ."; charset=utf-8\n\n";
783         print entityize($feed->toString) . "\n";
784
785         return Apache2::Const::OK;
786 }
787
788 sub opensearch_osd {
789         my $version = shift;
790         my $lib = shift;
791         my $class = shift;
792         my $base = shift;
793
794         if ($version eq '1.0') {
795                 print <<OSD;
796 Content-type: application/opensearchdescription+xml; charset=utf-8
797
798 <?xml version="1.0" encoding="UTF-8"?>
799 <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearchdescription/1.0/">
800   <Url>$base/1.0/$lib/-/$class/?searchTerms={searchTerms}&startPage={startPage}&amp;startIndex={startIndex}&amp;count={count}</Url>
801   <Format>http://a9.com/-/spec/opensearchrss/1.0/</Format>
802   <ShortName>$lib</ShortName>
803   <LongName>Search $lib</LongName>
804   <Description>Search the $lib OPAC by $class.</Description>
805   <Tags>$lib book library</Tags>
806   <SampleSearch>harry+potter</SampleSearch>
807   <Developer>Mike Rylander for GPLS/PINES</Developer>
808   <Contact>feedback\@open-ils.org</Contact>
809   <SyndicationRight>open</SyndicationRight>
810   <AdultContent>false</AdultContent>
811 </OpenSearchDescription>
812 OSD
813         } else {
814                 print <<OSD;
815 Content-type: application/opensearchdescription+xml; charset=utf-8
816
817 <?xml version="1.0" encoding="UTF-8"?>
818 <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">
819   <ShortName>$lib</ShortName>
820   <Description>Search the $lib OPAC by $class.</Description>
821   <Tags>$lib book library</Tags>
822   <Url type="application/rss+xml"
823        template="$base/1.1/$lib/rss2/$class/?searchTerms={searchTerms}&startPage={startPage?}&amp;startIndex={startIndex?}&amp;count={count?}&amp;searchLang={language?}"/>
824   <Url type="application/atom+xml"
825        template="$base/1.1/$lib/atom/$class/?searchTerms={searchTerms}&startPage={startPage?}&amp;startIndex={startIndex?}&amp;count={count?}&amp;searchLang={language?}"/>
826   <Url type="application/x-mods3+xml"
827        template="$base/1.1/$lib/mods3/$class/?searchTerms={searchTerms}&startPage={startPage?}&amp;startIndex={startIndex?}&amp;count={count?}&amp;searchLang={language?}"/>
828   <Url type="application/x-mods+xml"
829        template="$base/1.1/$lib/mods/$class/?searchTerms={searchTerms}&startPage={startPage?}&amp;startIndex={startIndex?}&amp;count={count?}&amp;searchLang={language?}"/>
830   <Url type="application/x-marcxml+xml"
831        template="$base/1.1/$lib/marcxml/$class/?searchTerms={searchTerms}&startPage={startPage?}&amp;startIndex={startIndex?}&amp;count={count?}&amp;searchLang={language?}"/>
832   <LongName>Search $lib</LongName>
833   <Query role="example" searchTerms="harry+potter" />
834   <Developer>Mike Rylander for GPLS/PINES</Developer>
835   <Contact>feedback\@open-ils.org</Contact>
836   <SyndicationRight>open</SyndicationRight>
837   <AdultContent>false</AdultContent>
838   <Language>en-US</Language>
839   <OutputEncoding>UTF-8</OutputEncoding>
840   <InputEncoding>UTF-8</InputEncoding>
841 </OpenSearchDescription>
842 OSD
843         }
844
845         return Apache2::Const::OK;
846 }
847
848 sub opensearch_feed {
849         my $apache = shift;
850         return Apache2::Const::DECLINED if (-e $apache->filename);
851
852         my $cgi = new CGI;
853         my $year = (gmtime())[5] + 1900;
854
855         my $host = $cgi->virtual_host || $cgi->server_name;
856
857         my $add_path = 0;
858         if ( $cgi->server_software !~ m|^Apache/2.2| ) {
859                 my $rel_name = $cgi->url(-relative=>1);
860                 $add_path = 1 if ($cgi->url(-path_info=>1) !~ /$rel_name$/);
861         }
862
863         my $url = $cgi->url(-path_info=>$add_path);
864         my $root = (split 'opensearch', $url)[0];
865         my $base = (split 'opensearch', $url)[0] . 'opensearch';
866         my $unapi = (split 'opensearch', $url)[0] . 'unapi';
867
868         my $path = $cgi->path_info;
869         #warn "URL breakdown: $url ($rel_name) -> $root -> $base -> $path -> $unapi";
870
871         if ($path =~ m{^/?(1\.\d{1})/(?:([^/]+)/)?([^/]+)/osd.xml}o) {
872                 
873                 my $version = $1;
874                 my $lib = $2;
875                 my $class = $3;
876
877                 if (!$lib) {
878                         $lib = $actor->request(
879                                 'open-ils.actor.org_unit_list.search' => parent_ou => undef
880                         )->gather(1)->[0]->shortname;
881                 }
882
883                 if ($class eq '-') {
884                         $class = 'keyword';
885                 }
886
887                 return opensearch_osd($version, $lib, $class, $base);
888         }
889
890
891         my $page = $cgi->param('startPage') || 1;
892         my $offset = $cgi->param('startIndex') || 1;
893         my $limit = $cgi->param('count') || 10;
894
895         $page = 1 if ($page !~ /^\d+$/);
896         $offset = 1 if ($offset !~ /^\d+$/);
897         $limit = 10 if ($limit !~ /^\d+$/); $limit = 25 if ($limit > 25);
898
899         if ($page > 1) {
900                 $offset = ($page - 1) * $limit;
901         } else {
902                 $offset -= 1;
903         }
904
905         my ($version,$org,$type,$class,$terms,$sort,$sortdir,$lang);
906         (undef,$version,$org,$type,$class,$terms,$sort,$sortdir,$lang) = split '/', $path;
907
908         $lang ||= $cgi->param('searchLang');
909         $sort ||= $cgi->param('searchSort');
910         $sortdir ||= $cgi->param('searchSortDir');
911         $terms ||= $cgi->param('searchTerms');
912         $class ||= $cgi->param('searchClass') || '-';
913         $type ||= $cgi->param('responseType') || '-';
914         $org ||= $cgi->param('searchOrg') || '-';
915
916         if ($version eq '1.0') {
917                 $type = 'rss2';
918         } elsif ($type eq '-') {
919                 $type = 'atom';
920         }
921         my $flesh_feed = ($type =~ /-full$/o) ? 1 : 0;
922
923         $terms = decode_utf8($terms);
924         $terms =~ s/\+/ /go;
925         $terms =~ s/'//go;
926         my $term_copy = $terms;
927
928         my $complex_terms = 0;
929         if ($terms eq 'help') {
930                 print $cgi->header(-type => 'text/html');
931                 print <<"               HTML";
932                         <html>
933                          <head>
934                           <title>just type something!</title>
935                          </head>
936                          <body>
937                           <p>You are in a maze of dark, twisty stacks, all alike.</p>
938                          </body>
939                         </html>
940                 HTML
941                 return Apache2::Const::OK;
942         }
943
944         my $cache_key = '';
945         my $searches = {};
946         while ($term_copy =~ s/((?:keyword|title|author|subject|series|site|dir|sort|lang):[^:]+)$//so) {
947                 my ($c,$t) = split ':' => $1;
948                 if ($c eq 'site') {
949                         $org = $t;
950                         $org =~ s/^\s*//o;
951                         $org =~ s/\s*$//o;
952                 } elsif ($c eq 'sort') {
953                         ($sort = lc($t)) =~ s/^\s*(\w+)\s*$/$1/go;
954                 } elsif ($c eq 'dir') {
955                         ($sortdir = lc($t)) =~ s/^\s*(\w+)\s*$/$1/go;
956                 } elsif ($c eq 'lang') {
957                         ($lang = lc($t)) =~ s/^\s*(\w+)\s*$/$1/go;
958                 } else {
959                         $$searches{$c}{term} .= ' '.$t;
960                         $cache_key .= $c . $t;
961                         $complex_terms = 1;
962                 }
963         }
964
965         if ($term_copy) {
966                 no warnings;
967                 $class = 'keyword' if ($class eq '-');
968                 $$searches{$class}{term} .= " $term_copy";
969                 $cache_key .= $class . $term_copy;
970         }
971
972         my $org_unit;
973         if ($org eq '-') {
974                 $org_unit = $actor->request(
975                         'open-ils.actor.org_unit_list.search' => parent_ou => undef
976                 )->gather(1);
977         } else {
978                 $org_unit = $actor->request(
979                         'open-ils.actor.org_unit_list.search' => shortname => uc($org)
980                 )->gather(1);
981         }
982
983         $cache_key .= $org.$sort.$sortdir.$lang;
984
985         my $rs_name = $cgi->cookie('os_session');
986         my $cached_res = OpenSRF::Utils::Cache->new->get_cache( "os_session:$rs_name" ) if ($rs_name);
987
988         my $recs;
989         if (!($recs = $$cached_res{os_results}{$cache_key})) {
990                 $rs_name = $cgi->remote_host . '::' . rand(time);
991                 $recs = $search->request(
992                         'open-ils.search.biblio.multiclass' => {
993                                 searches        => $searches,
994                                 org_unit        => $org_unit->[0]->id,
995                                 offset          => 0,
996                                 limit           => 5000,
997                                 ($sort ?    ( 'sort'     => $sort    ) : ()),
998                                 ($sortdir ? ( 'sort_dir' => $sortdir ) : ($sort ? (sort_dir => 'asc') : (sort_dir => 'desc') )),
999                                 ($lang ?    ( 'language' => $lang    ) : ()),
1000                         }
1001                 )->gather(1);
1002                 try {
1003                         $$cached_res{os_results}{$cache_key} = $recs;
1004                         OpenSRF::Utils::Cache->new->put_cache( "os_session:$rs_name", $cached_res, 1800 );
1005                 } catch Error with {
1006                         warn "supercat unable to store IDs in memcache server\n";
1007                         $logger->error("supercat unable to store IDs in memcache server");
1008                 };
1009         }
1010
1011         my $feed = create_record_feed(
1012                 'record',
1013                 $type,
1014                 [ map { $_->[0] } @{$recs->{ids}}[$offset .. $offset + $limit - 1] ],
1015                 $unapi,
1016                 $org,
1017                 $flesh_feed
1018         );
1019         $feed->root($root);
1020         $feed->lib($org);
1021         $feed->search($terms);
1022         $feed->class($class);
1023
1024         if ($complex_terms) {
1025                 $feed->title("Search results for [$terms] at ".$org_unit->[0]->name);
1026         } else {
1027                 $feed->title("Search results for [$class => $terms] at ".$org_unit->[0]->name);
1028         }
1029
1030         $feed->creator($host);
1031         $feed->update_ts(gmtime_ISO8601());
1032
1033         $feed->_create_node(
1034                 $feed->{item_xpath},
1035                 'http://a9.com/-/spec/opensearch/1.1/',
1036                 'totalResults',
1037                 $recs->{count},
1038         );
1039
1040         $feed->_create_node(
1041                 $feed->{item_xpath},
1042                 'http://a9.com/-/spec/opensearch/1.1/',
1043                 'startIndex',
1044                 $offset + 1,
1045         );
1046
1047         $feed->_create_node(
1048                 $feed->{item_xpath},
1049                 'http://a9.com/-/spec/opensearch/1.1/',
1050                 'itemsPerPage',
1051                 $limit,
1052         );
1053
1054         $feed->link(
1055                 next =>
1056                 $base . "/$version/$org/$type/$class?searchTerms=$terms&startIndex=" . int($offset + $limit + 1) . "&count=" . $limit =>
1057                 'application/opensearch+xml'
1058         ) if ($offset + $limit < $recs->{count});
1059
1060         $feed->link(
1061                 previous =>
1062                 $base . "/$version/$org/$type/$class?searchTerms=$terms&startIndex=" . int(($offset - $limit) + 1) . "&count=" . $limit =>
1063                 'application/opensearch+xml'
1064         ) if ($offset);
1065
1066         $feed->link(
1067                 self =>
1068                 $base .  "/$version/$org/$type/$class?searchTerms=$terms" =>
1069                 'application/opensearch+xml'
1070         );
1071
1072         $feed->link(
1073                 rss =>
1074                 $base .  "/$version/$org/rss2-full/$class?searchTerms=$terms" =>
1075                 'application/rss+xml'
1076         );
1077
1078         $feed->link(
1079                 alternate =>
1080                 $base .  "/$version/$org/atom-full/$class?searchTerms=$terms" =>
1081                 'application/atom+xml'
1082         );
1083
1084         $feed->link(
1085                 'html' =>
1086                 $base .  "/$version/$org/html/$class?searchTerms=$terms" =>
1087                 'text/html'
1088         );
1089
1090         $feed->link(
1091                 'html-full' =>
1092                 $base .  "/$version/$org/html-full/$class?searchTerms=$terms" =>
1093                 'text/html'
1094         );
1095
1096         $feed->link( 'unapi-server' => $unapi);
1097
1098 #       $feed->link(
1099 #               opac =>
1100 #               $root . "../$lang/skin/default/xml/rresult.xml?rt=list&" .
1101 #                       join('&', map { 'rl=' . $_->[0] } grep { ref $_ && defined $_->[0] } @{$recs->{ids}} ),
1102 #               'text/html'
1103 #       );
1104
1105         print $cgi->header(
1106                 -type           => $feed->type,
1107                 -charset        => 'UTF-8',
1108                 -cookie         => $cgi->cookie( -name => 'os_session', -value => $rs_name, -expires => '+30m' ),
1109         );
1110
1111         print entityize($feed->toString) . "\n";
1112
1113         return Apache2::Const::OK;
1114 }
1115
1116 sub create_record_feed {
1117         my $search = shift;
1118         my $type = shift;
1119         my $records = shift;
1120         my $unapi = shift;
1121
1122         my $lib = shift || '-';
1123         my $flesh = shift;
1124         $flesh = 1 if (!defined($flesh));
1125
1126         my $cgi = new CGI;
1127         my $base = $cgi->url;
1128         my $host = $cgi->virtual_host || $cgi->server_name;
1129
1130         my $year = (gmtime())[5] + 1900;
1131
1132         my $flesh_feed = ($type =~ s/-full$//o) ? 1 : 0;
1133
1134         my $feed = new OpenILS::WWW::SuperCat::Feed ($type);
1135         $feed->base($base) if ($flesh);
1136         $feed->unapi($unapi) if ($flesh);
1137
1138         $type = 'atom' if ($type eq 'html');
1139         $type = 'marcxml' if ($type eq 'htmlholdings');
1140
1141         #$records = $supercat->request( "open-ils.supercat.record.object.retrieve", $records )->gather(1);
1142
1143         my $count = 0;
1144         for my $record (@$records) {
1145                 next unless($record);
1146
1147                 #my $rec = $record->id;
1148                 my $rec = $record;
1149
1150                 my $item_tag = "tag:$host,$year:biblio-record_entry/$rec/$lib";
1151                 $item_tag = "tag:$host,$year:isbn/$rec/$lib" if ($search eq 'isbn');
1152
1153                 my $xml = $supercat->request(
1154                         "open-ils.supercat.$search.$type.retrieve",
1155                         $rec
1156                 )->gather(1);
1157                 next unless $xml;
1158
1159                 my $node = $feed->add_item($xml);
1160                 next unless $node;
1161
1162                 if ($lib && $type eq 'marcxml' &&  $flesh) {
1163                         $xml = $supercat->request( "open-ils.supercat.$search.holdings_xml.retrieve", $rec, $lib )->gather(1);
1164                         $node->add_holdings($xml);
1165                 }
1166
1167                 $node->id($item_tag) if ($flesh);
1168                 #$node->update_ts(clense_ISO8601($record->edit_date));
1169                 $node->link(alternate => $feed->unapi . "?id=$item_tag&format=htmlholdings-full" => 'text/html') if ($flesh);
1170                 $node->link(opac => $feed->unapi . "?id=$item_tag&format=opac") if ($flesh);
1171                 $node->link(unapi => $feed->unapi . "?id=$item_tag") if ($flesh);
1172                 $node->link('unapi-id' => $item_tag) if ($flesh);
1173         }
1174
1175         return $feed;
1176 }
1177
1178 sub entityize {
1179         my $stuff = NFC(shift());
1180         $stuff =~ s/&(?!\S+;)/&amp;/gso;
1181         $stuff =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
1182         return $stuff;
1183 }
1184
1185 sub string_browse {
1186         my $apache = shift;
1187         return Apache2::Const::DECLINED if (-e $apache->filename);
1188
1189         my $cgi = new CGI;
1190         my $year = (gmtime())[5] + 1900;
1191
1192         my $host = $cgi->virtual_host || $cgi->server_name;
1193
1194         my $add_path = 0;
1195         if ( $cgi->server_software !~ m|^Apache/2.2| ) {
1196                 my $rel_name = $cgi->url(-relative=>1);
1197                 $add_path = 1 if ($cgi->url(-path_info=>1) !~ /$rel_name$/);
1198         }
1199
1200         my $url = $cgi->url(-path_info=>$add_path);
1201         my $root = (split 'browse', $url)[0];
1202         my $base = (split 'browse', $url)[0] . 'browse';
1203         my $unapi = (split 'browse', $url)[0] . 'unapi';
1204
1205         my $path = $cgi->path_info;
1206         $path =~ s/^\///og;
1207
1208         my ($format,$axis,$site,$string,$page,$page_size) = split '/', $path;
1209         #warn " >>> $format -> $axis -> $site -> $string -> $page -> $page_size ";
1210
1211         $site ||= $cgi->param('searchOrg');
1212         $page ||= $cgi->param('startPage') || 0;
1213         $page_size ||= $cgi->param('count') || 9;
1214
1215         $page = 0 if ($page !~ /^-?\d+$/);
1216
1217         my $prev = join('/', $base,$format,$axis,$site,$string,$page - 1,$page_size);
1218         my $next = join('/', $base,$format,$axis,$site,$string,$page + 1,$page_size);
1219
1220         unless ($string and $axis and grep { $axis eq $_ } keys %browse_types) {
1221                 warn "something's wrong...";
1222                 warn " >>> $format -> $axis -> $site -> $string -> $page -> $page_size ";
1223                 return undef;
1224         }
1225
1226         $string = decode_utf8($string);
1227         $string =~ s/\+/ /go;
1228         $string =~ s/'//go;
1229
1230         my $tree = $supercat->request(
1231                 "open-ils.supercat.$axis.browse",
1232                 $string,
1233                 $site,
1234                 $page_size,
1235                 $page
1236         )->gather(1);
1237
1238         my ($header,$content) = $browse_types{$axis}{$format}->($tree,$prev,$next);
1239         print $header.$content;
1240         return Apache2::Const::OK;
1241 }
1242
1243 1;