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