]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/WWW/SuperCat.pm
improving unapi support
[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 $path = (split 'supercat', $url)[1];
259         my $unapi = (split 'supercat', $url)[0] . 'unapi';
260
261         my $host = $cgi->virtual_host || $cgi->server_name;
262
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 $path = (split 'bookbag', $url)[1];
430         my $unapi = (split 'feed', $url)[0] . 'unapi';
431
432
433         #warn "URL breakdown: $url ($rel_name) -> $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 $path = (split 'freshmeat', $url)[1];
497         my $unapi = (split 'feed', $url)[0] . 'unapi';
498
499
500         #warn "URL breakdown: $url ($rel_name) -> $root -> $base -> $path -> $unapi";
501
502         $path =~ s/^\///og;
503         
504         my ($type,$rtype,$axis,$limit,$date) = split '/', $path;
505         $limit ||= 10;
506
507         my $list = $supercat->request("open-ils.supercat.$rtype.record.$axis.recent", $date, $limit)->gather(1);
508
509         if ($type eq 'opac') {
510                 print "Location: $root/../../en-US/skin/default/xml/rresult.xml?rt=list&" .
511                         join('&', map { "rl=" . $_ } @$list) .
512                         "\n\n";
513                 return 302;
514         }
515
516         my $feed = create_record_feed( $type, $list, $unapi);
517         $feed->root($root);
518
519         if ($date) {
520                 $feed->title("Up to $limit recent $rtype ${axis}s from $date forward");
521         } else {
522                 $feed->title("$limit most recent $rtype ${axis}s");
523         }
524
525         $feed->creator($host);
526         $feed->update_ts(gmtime_ISO8601());
527
528         $feed->link(rss => $base . "/rss2/$rtype/$axis/$limit/$date" => 'application/rss+xml');
529         $feed->link(alternate => $base . "/atom/$rtype/$axis/$limit/$date" => 'application/atom+xml');
530         $feed->link(html => $base . "/html/$rtype/$axis/$limit/$date" => 'text/html');
531         $feed->link(unapi => $unapi);
532
533         $feed->link(
534                 OPAC =>
535                 '/opac/en-US/skin/default/xml/rresult.xml?rt=list&' .
536                         join('&', map { 'rl=' . $_} @$list ),
537                 'text/html'
538         );
539
540
541         print "Content-type: ". $feed->type ."; charset=utf-8\n\n";
542         print entityize($feed->toString) . "\n";
543
544         return Apache2::Const::OK;
545 }
546
547 sub opensearch_osd {
548         my $version = shift;
549         my $lib = shift;
550         my $class = shift;
551         my $base = shift;
552
553         if ($version eq '1.0') {
554                 print <<OSD;
555 Content-type: application/opensearchdescription+xml; charset=utf-8
556
557 <?xml version="1.0" encoding="UTF-8"?>
558 <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearchdescription/1.0/">
559   <Url>$base/1.0/$lib/-/$class/?searchTerms={searchTerms}&startPage={startPage}&amp;startIndex={startIndex}&amp;count={count}</Url>
560   <Format>http://a9.com/-/spec/opensearchrss/1.0/</Format>
561   <ShortName>$lib</ShortName>
562   <LongName>Search $lib</LongName>
563   <Description>Search the $lib OPAC by $class.</Description>
564   <Tags>$lib book library</Tags>
565   <SampleSearch>harry+potter</SampleSearch>
566   <Developer>Mike Rylander for GPLS/PINES</Developer>
567   <Contact>feedback\@open-ils.org</Contact>
568   <SyndicationRight>open</SyndicationRight>
569   <AdultContent>false</AdultContent>
570 </OpenSearchDescription>
571 OSD
572         } else {
573                 print <<OSD;
574 Content-type: application/opensearchdescription+xml; charset=utf-8
575
576 <?xml version="1.0" encoding="UTF-8"?>
577 <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">
578   <ShortName>$lib</ShortName>
579   <Description>Search the $lib OPAC by $class.</Description>
580   <Tags>$lib book library</Tags>
581   <Url type="application/rss+xml"
582        template="$base/1.1/$lib/rss2/$class/?searchTerms={searchTerms}&startPage={startPage?}&amp;startIndex={startIndex?}&amp;count={count?}&amp;searchLang={language?}"/>
583   <Url type="application/atom+xml"
584        template="$base/1.1/$lib/atom/$class/?searchTerms={searchTerms}&startPage={startPage?}&amp;startIndex={startIndex?}&amp;count={count?}&amp;searchLang={language?}"/>
585   <Url type="application/x-mods3+xml"
586        template="$base/1.1/$lib/mods3/$class/?searchTerms={searchTerms}&startPage={startPage?}&amp;startIndex={startIndex?}&amp;count={count?}&amp;searchLang={language?}"/>
587   <Url type="application/x-mods+xml"
588        template="$base/1.1/$lib/mods/$class/?searchTerms={searchTerms}&startPage={startPage?}&amp;startIndex={startIndex?}&amp;count={count?}&amp;searchLang={language?}"/>
589   <Url type="application/x-marcxml+xml"
590        template="$base/1.1/$lib/marcxml/$class/?searchTerms={searchTerms}&startPage={startPage?}&amp;startIndex={startIndex?}&amp;count={count?}&amp;searchLang={language?}"/>
591   <LongName>Search $lib</LongName>
592   <Query role="example" searchTerms="harry+potter" />
593   <Developer>Mike Rylander for GPLS/PINES</Developer>
594   <Contact>feedback\@open-ils.org</Contact>
595   <SyndicationRight>open</SyndicationRight>
596   <AdultContent>false</AdultContent>
597   <Language>en-US</Language>
598   <OutputEncoding>UTF-8</OutputEncoding>
599   <InputEncoding>UTF-8</InputEncoding>
600 </OpenSearchDescription>
601 OSD
602         }
603
604         return Apache2::Const::OK;
605 }
606
607 sub opensearch_feed {
608         my $apache = shift;
609         return Apache2::Const::DECLINED if (-e $apache->filename);
610
611         my $cgi = new CGI;
612         my $year = (gmtime())[5] + 1900;
613
614         my $host = $cgi->virtual_host || $cgi->server_name;
615
616         my $add_path = 0;
617         if ( $cgi->server_software !~ m|^Apache/2.2| ) {
618                 my $rel_name = $cgi->url(-relative=>1);
619                 $add_path = 1 if ($cgi->url(-path_info=>1) !~ /$rel_name$/);
620         }
621
622         my $url = $cgi->url(-path_info=>$add_path);
623         my $root = (split 'opensearch', $url)[0];
624         my $base = (split 'opensearch', $url)[0] . 'opensearch';
625         my $unapi = (split 'opensearch', $url)[0] . 'unapi';
626
627
628         my $path = $cgi->path_info;
629
630         #warn "URL breakdown: $url ($rel_name) -> $root -> $base -> $path -> $unapi";
631
632         if ($path =~ m{^/?(1\.\d{1})/(?:([^/]+)/)?([^/]+)/osd.xml}o) {
633                 
634                 my $version = $1;
635                 my $lib = $2;
636                 my $class = $3;
637
638                 if (!$lib) {
639                         $lib = $actor->request(
640                                 'open-ils.actor.org_unit_list.search' => parent_ou => undef
641                         )->gather(1)->[0]->shortname;
642                 }
643
644                 if ($class eq '-') {
645                         $class = 'keyword';
646                 }
647
648                 return opensearch_osd($version, $lib, $class, $base);
649         }
650
651
652         my $page = $cgi->param('startPage') || 1;
653         my $offset = $cgi->param('startIndex') || 1;
654         my $limit = $cgi->param('count') || 10;
655
656         $page = 1 if ($page !~ /^\d+$/);
657         $offset = 1 if ($offset !~ /^\d+$/);
658         $limit = 10 if ($limit !~ /^\d+$/); $limit = 25 if ($limit > 25);
659
660         if ($page > 1) {
661                 $offset = ($page - 1) * $limit;
662         } else {
663                 $offset -= 1;
664         }
665
666         my ($version,$org,$type,$class,$terms,$sort,$sortdir,$lang);
667         (undef,$version,$org,$type,$class,$terms,$sort,$sortdir,$lang) = split '/', $path;
668
669         $lang ||= $cgi->param('searchLang');
670         $sort ||= $cgi->param('searchSort');
671         $sortdir ||= $cgi->param('searchSortDir');
672         $terms ||= $cgi->param('searchTerms');
673         $class ||= $cgi->param('searchClass') || '-';
674         $type ||= $cgi->param('responseType') || '-';
675         $org ||= $cgi->param('searchOrg') || '-';
676
677         if ($version eq '1.0') {
678                 $type = 'rss2';
679         } elsif ($type eq '-') {
680                 $type = 'atom';
681         }
682
683
684         $terms = decode_utf8($terms);
685         $terms =~ s/\+/ /go;
686         $terms =~ s/'//go;
687         my $term_copy = $terms;
688
689         my $complex_terms = 0;
690         if ($terms eq 'help') {
691                 print $cgi->header(-type => 'text/html');
692                 print <<"               HTML";
693                         <html>
694                          <head>
695                           <title>just type something!</title>
696                          </head>
697                          <body>
698                           <p>You are in a maze of dark, twisty stacks, all alike.</p>
699                          </body>
700                         </html>
701                 HTML
702                 return Apache2::Const::OK;
703         }
704
705         my $cache_key = '';
706         my $searches = {};
707         while ($term_copy =~ s/((?:keyword|title|author|subject|series|site|dir|sort|lang):[^:]+)$//so) {
708                 my ($c,$t) = split ':' => $1;
709                 if ($c eq 'site') {
710                         $org = $t;
711                         $org =~ s/^\s*//o;
712                         $org =~ s/\s*$//o;
713                 } elsif ($c eq 'sort') {
714                         ($sort = lc($t)) =~ s/^\s*(\w+)\s*$/$1/go;
715                 } elsif ($c eq 'dir') {
716                         ($sortdir = lc($t)) =~ s/^\s*(\w+)\s*$/$1/go;
717                 } elsif ($c eq 'lang') {
718                         ($lang = lc($t)) =~ s/^\s*(\w+)\s*$/$1/go;
719                 } else {
720                         $$searches{$c}{term} .= ' '.$t;
721                         $cache_key .= $c . $t;
722                         $complex_terms = 1;
723                 }
724         }
725
726         if ($term_copy) {
727                 no warnings;
728                 $class = 'keyword' if ($class eq '-');
729                 $$searches{$class}{term} .= " $term_copy";
730                 $cache_key .= $class . $term_copy;
731         }
732
733         my $org_unit;
734         if ($org eq '-') {
735                 $org_unit = $actor->request(
736                         'open-ils.actor.org_unit_list.search' => parent_ou => undef
737                 )->gather(1);
738         } else {
739                 $org_unit = $actor->request(
740                         'open-ils.actor.org_unit_list.search' => shortname => uc($org)
741                 )->gather(1);
742         }
743
744         $cache_key .= $org.$sort.$sortdir.$lang;
745
746         my $rs_name = $cgi->cookie('os_session');
747         my $cached_res = OpenSRF::Utils::Cache->new->get_cache( "os_session:$rs_name" ) if ($rs_name);
748
749         my $recs;
750         if (!($recs = $$cached_res{os_results}{$cache_key})) {
751                 $rs_name = $cgi->remote_host . '::' . rand(time);
752                 $recs = $search->request(
753                         'open-ils.search.biblio.multiclass' => {
754                                 searches        => $searches,
755                                 org_unit        => $org_unit->[0]->id,
756                                 offset          => 0,
757                                 limit           => 5000,
758                                 ($sort ?    ( 'sort'     => $sort    ) : ()),
759                                 ($sortdir ? ( 'sort_dir' => $sortdir ) : ($sort ? (sort_dir => 'asc') : (sort_dir => 'desc') )),
760                                 ($lang ?    ( 'language' => $lang    ) : ()),
761                         }
762                 )->gather(1);
763                 try {
764                         $$cached_res{os_results}{$cache_key} = $recs;
765                         OpenSRF::Utils::Cache->new->put_cache( "os_session:$rs_name", $cached_res, 1800 );
766                 } catch Error with {
767                         warn shift();
768                 };
769         }
770
771         my $feed = create_record_feed(
772                 $type,
773                 [ map { $_->[0] } @{$recs->{ids}}[$offset .. $offset + $limit - 1] ],
774                 $unapi,
775                 $org
776         );
777         $feed->root($root);
778         $feed->lib($org);
779         $feed->search($terms);
780         $feed->class($class);
781
782         if ($complex_terms) {
783                 $feed->title("Search results for [$terms] at ".$org_unit->[0]->name);
784         } else {
785                 $feed->title("Search results for [$class => $terms] at ".$org_unit->[0]->name);
786         }
787
788         $feed->creator($host);
789         $feed->update_ts(gmtime_ISO8601());
790
791         $feed->_create_node(
792                 $feed->{item_xpath},
793                 'http://a9.com/-/spec/opensearch/1.1/',
794                 'totalResults',
795                 $recs->{count},
796         );
797
798         $feed->_create_node(
799                 $feed->{item_xpath},
800                 'http://a9.com/-/spec/opensearch/1.1/',
801                 'startIndex',
802                 $offset + 1,
803         );
804
805         $feed->_create_node(
806                 $feed->{item_xpath},
807                 'http://a9.com/-/spec/opensearch/1.1/',
808                 'itemsPerPage',
809                 $limit,
810         );
811
812         $feed->link(
813                 next =>
814                 $base . "/$version/$org/$type/$class?searchTerms=$terms&startIndex=" . int($offset + $limit + 1) . "&count=" . $limit =>
815                 'application/opensearch+xml'
816         ) if ($offset + $limit < $recs->{count});
817
818         $feed->link(
819                 previous =>
820                 $base . "/$version/$org/$type/$class?searchTerms=$terms&startIndex=" . int(($offset - $limit) + 1) . "&count=" . $limit =>
821                 'application/opensearch+xml'
822         ) if ($offset);
823
824         $feed->link(
825                 self =>
826                 $base .  "/$version/$org/$type/$class?searchTerms=$terms" =>
827                 'application/opensearch+xml'
828         );
829
830         $feed->link(
831                 rss =>
832                 $base .  "/$version/$org/rss2/$class?searchTerms=$terms" =>
833                 'application/rss+xml'
834         );
835
836         $feed->link(
837                 alternate =>
838                 $base .  "/$version/$org/atom/$class?searchTerms=$terms" =>
839                 'application/atom+xml'
840         );
841
842         $feed->link(
843                 html =>
844                 $base .  "/$version/$org/html/$class?searchTerms=$terms" =>
845                 'text/html'
846         );
847
848         $feed->link( unapi => $unapi);
849
850         $feed->link(
851                 opac =>
852                 $root . "../$lang/skin/default/xml/rresult.xml?rt=list&" .
853                         join('&', map { 'rl=' . $_->[0] } grep { ref $_ && defined $_->[0] } @{$recs->{ids}} ),
854                 'text/html'
855         );
856
857         print $cgi->header(
858                 -type           => $feed->type,
859                 -charset        => 'UTF-8',
860                 -cookie         => $cgi->cookie( -name => 'os_session', -value => $rs_name, -expires => '+30m' ),
861         );
862
863         print entityize($feed->toString) . "\n";
864
865         return Apache2::Const::OK;
866 }
867
868 sub create_record_feed {
869         my $type = shift;
870         my $records = shift;
871         my $unapi = shift;
872
873         my $lib = shift || '-';
874
875         my $cgi = new CGI;
876         my $base = $cgi->url;
877         my $host = $cgi->virtual_host || $cgi->server_name;
878
879         my $year = (gmtime())[5] + 1900;
880
881         my $feed = new OpenILS::WWW::SuperCat::Feed ($type);
882         $feed->base($base);
883         $feed->unapi($unapi);
884
885         $type = 'atom' if ($type eq 'html');
886         $type = 'marcxml' if ($type eq 'htmlcard' or $type eq 'htmlholdings');
887
888         #$records = $supercat->request( "open-ils.supercat.record.object.retrieve", $records )->gather(1);
889
890         for my $record (@$records) {
891                 next unless($record);
892
893                 #my $rec = $record->id;
894                 my $rec = $record;
895
896                 my $item_tag = "tag:$host,$year:biblio-record_entry/$rec/$lib";
897
898                 my $xml = $supercat->request(
899                         "open-ils.supercat.record.$type.retrieve",
900                         $rec
901                 )->gather(1);
902                 next unless $xml;
903
904                 my $node = $feed->add_item($xml);
905                 next unless $node;
906
907                 if ($lib && $type eq 'marcxml') {
908                         $xml = $supercat->request( "open-ils.supercat.record.holdings_xml.retrieve", $rec, $lib )->gather(1);
909                         $node->add_holdings($xml);
910                 }
911
912                 $node->id($item_tag);
913                 #$node->update_ts(clense_ISO8601($record->edit_date));
914                 $node->link(alternate => $feed->unapi . "?id=$item_tag&format=htmlholdings" => 'text/html');
915                 $node->link(opac => $feed->unapi . "?id=$item_tag&format=opac");
916                 $node->link(unapi => $feed->unapi . "?id=$item_tag");
917                 $node->link('unapi-id' => $item_tag);
918         }
919
920         return $feed;
921 }
922
923 sub entityize {
924         my $stuff = NFC(shift());
925         $stuff =~ s/&(?!\S+;)/&amp;/gso;
926         $stuff =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
927         return $stuff;
928 }
929
930 my %browse_types = (
931         call_number => {
932                 xml => sub {
933                         my $tree = shift;
934
935                         my $year = (gmtime())[5] + 1900;
936                         my $content = '';
937
938                         $content .= "Content-type: application/xml\n\n";
939                         $content .= "<hold:volumes  xmlns:hold='http://open-ils.org/spec/holdings/v1'>";
940
941                         for my $cn (@$tree) {
942                                 (my $cn_class = $cn->class_name) =~ s/::/-/gso;
943                                 $cn_class =~ s/Fieldmapper-//gso;
944
945                                 my $cn_tag = "tag:open-ils.org,$year:$cn_class/".$cn->id;
946                                 my $cn_lib = $cn->owning_lib->shortname;
947                                 my $cn_label = $cn->label;
948
949                                 (my $ou_class = $cn->owning_lib->class_name) =~ s/::/-/gso;
950                                 $ou_class =~ s/Fieldmapper-//gso;
951
952                                 my $ou_tag = "tag:open-ils.org,$year:$ou_class/".$cn->owning_lib->id;
953                                 my $ou_name = $cn->owning_lib->name;
954
955                                 $content .= "<hold:volume id='$cn_tag' lib='$cn_lib' label='$cn_label'>";
956                                 $content .= "<act:owning_lib xmlns:act='http://open-ils.org/spec/actors/v1' id='$ou_tag' name='$ou_name'/>";
957                                 $content .= $cn->record->marc;
958                                 $content .= "</hold:volume>";
959                         }
960
961                         $content .= '</hold:volumes>';
962                         return $content;
963                 }
964         }
965                         
966 );
967 sub string_browse {
968         my $apache = shift;
969         return Apache2::Const::DECLINED if (-e $apache->filename);
970
971         my $cgi = new CGI;
972         my $year = (gmtime())[5] + 1900;
973
974         my $host = $cgi->virtual_host || $cgi->server_name;
975
976         my $add_path = 0;
977         if ( $cgi->server_software !~ m|^Apache/2.2| ) {
978                 my $rel_name = $cgi->url(-relative=>1);
979                 $add_path = 1 if ($cgi->url(-path_info=>1) !~ /$rel_name$/);
980         }
981
982         my $url = $cgi->url(-path_info=>$add_path);
983         my $root = (split 'browse', $url)[0];
984         my $base = (split 'browse', $url)[0] . 'browse';
985         my $unapi = (split 'browse', $url)[0] . 'unapi';
986
987
988         my $path = (split 'browse', $url)[1];
989
990         my (undef,$format,$axis,$site,$string,$page,$page_size) = split '/', $path;
991
992
993         $site ||= $cgi->param('searchOrg');
994         $page ||= $cgi->param('startPage') || 0;
995         $page_size ||= $cgi->param('count') || 9;
996
997         $page = 0 if ($page !~ /^\d+$/);
998
999         unless ($string and $axis and grep { $axis eq $_ } keys %browse_types) {
1000                 warn "something's wrong...";
1001                 return undef;
1002         }
1003
1004         $string = decode_utf8($string);
1005         $string =~ s/\+/ /go;
1006         $string =~ s/'//go;
1007
1008         my $tree = $supercat->request(
1009                 "open-ils.supercat.$axis.browse",
1010                 $string,
1011                 $site,
1012                 $page_size,
1013                 $page
1014         )->gather(1);
1015
1016         my $content = $browse_types{$axis}{$format}->($tree);
1017         print $content;
1018         return Apache2::Const::OK;
1019 }
1020
1021 1;