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