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