71031acf01f8860050a68ff4b0e163bd459f8df2
[Evergreen.git] / Open-ILS / src / perlmods / OpenILS / WWW / SuperCat.pm
1 package OpenILS::WWW::SuperCat;
2 use strict; use warnings;
3
4 use Apache2::Log;
5 use Apache2::Const -compile => qw(OK REDIRECT DECLINED NOT_FOUND :log);
6 use APR::Const    -compile => qw(:error SUCCESS);
7 use Apache2::RequestRec ();
8 use Apache2::RequestIO ();
9 use Apache2::RequestUtil;
10 use CGI;
11 use Data::Dumper;
12 use SRU::Request;
13 use SRU::Response;
14
15 use OpenSRF::EX qw(:try);
16 use OpenSRF::Utils qw/:datetime/;
17 use OpenSRF::Utils::Cache;
18 use OpenSRF::System;
19 use OpenSRF::AppSession;
20 use XML::LibXML;
21 use XML::LibXSLT;
22
23 use Encode;
24 use Unicode::Normalize;
25 use OpenILS::Utils::Fieldmapper;
26 use OpenILS::WWW::SuperCat::Feed;
27 use OpenSRF::Utils::Logger qw/$logger/;
28
29 use MARC::Record;
30 use MARC::File::XML;
31
32 # set the bootstrap config when this module is loaded
33 my ($bootstrap, $cstore, $supercat, $actor, $parser, $search, $xslt, $cn_browse_xslt, %browse_types);
34
35 $browse_types{call_number}{xml} = sub {
36         my $tree = shift;
37
38         my $year = (gmtime())[5] + 1900;
39         my $content = '';
40
41         $content .= "<hold:volumes  xmlns:hold='http://open-ils.org/spec/holdings/v1'>";
42
43         for my $cn (@$tree) {
44                 (my $cn_class = $cn->class_name) =~ s/::/-/gso;
45                 $cn_class =~ s/Fieldmapper-//gso;
46
47                 my $cn_tag = "tag:open-ils.org,$year:$cn_class/".$cn->id;
48                 my $cn_lib = $cn->owning_lib->shortname;
49                 my $cn_label = $cn->label;
50
51                 $cn_label =~ s/\n//gos;
52                 $cn_label =~ s/'/&apos;/go;
53
54                 (my $ou_class = $cn->owning_lib->class_name) =~ s/::/-/gso;
55                 $ou_class =~ s/Fieldmapper-//gso;
56
57                 my $ou_tag = "tag:open-ils.org,$year:$ou_class/".$cn->owning_lib->id;
58                 my $ou_name = $cn->owning_lib->name;
59
60                 $ou_name =~ s/\n//gos;
61                 $ou_name =~ s/'/&apos;/go;
62
63                 (my $rec_class = $cn->record->class_name) =~ s/::/-/gso;
64                 $rec_class =~ s/Fieldmapper-//gso;
65
66                 my $rec_tag = "tag:open-ils.org,$year:$rec_class/".$cn->record->id.'/'.$cn->owning_lib->shortname;
67
68                 $content .= "<hold:volume id='$cn_tag' lib='$cn_lib' label='$cn_label'>";
69                 $content .= "<act:owning_lib xmlns:act='http://open-ils.org/spec/actors/v1' id='$ou_tag' name='$ou_name'/>";
70
71                 my $r_doc = $parser->parse_string($cn->record->marc);
72                 $r_doc->documentElement->setAttribute( id => $rec_tag );
73                 $content .= entityize($r_doc->documentElement->toString);
74
75                 $content .= "</hold:volume>";
76         }
77
78         $content .= '</hold:volumes>';
79         return ("Content-type: application/xml\n\n",$content);
80 };
81
82
83 $browse_types{call_number}{html} = sub {
84         my $tree = shift;
85         my $p = shift;
86         my $n = shift;
87
88         if (!$cn_browse_xslt) {
89                 $cn_browse_xslt = $parser->parse_file(
90                         OpenSRF::Utils::SettingsClient
91                                 ->new
92                                 ->config_value( dirs => 'xsl' ).
93                         "/CNBrowse2HTML.xsl"
94                 );
95                 $cn_browse_xslt = $xslt->parse_stylesheet( $cn_browse_xslt );
96         }
97
98         my (undef,$xml) = $browse_types{call_number}{xml}->($tree);
99
100         return (
101                 "Content-type: text/html\n\n",
102                 entityize(
103                         $cn_browse_xslt->transform(
104                                 $parser->parse_string( $xml ),
105                                 'prev' => "'$p'",
106                                 'next' => "'$n'"
107                         )->toString(1)
108                 )
109         );
110 };
111
112 sub import {
113         my $self = shift;
114         $bootstrap = shift;
115 }
116
117
118 sub child_init {
119         OpenSRF::System->bootstrap_client( config_file => $bootstrap );
120         
121         my $idl = OpenSRF::Utils::SettingsClient->new->config_value("IDL");
122         Fieldmapper->import(IDL => $idl);
123
124         $supercat = OpenSRF::AppSession->create('open-ils.supercat');
125         $cstore = OpenSRF::AppSession->create('open-ils.cstore');
126         $actor = OpenSRF::AppSession->create('open-ils.actor');
127         $search = OpenSRF::AppSession->create('open-ils.search');
128         $parser = new XML::LibXML;
129         $xslt = new XML::LibXSLT;
130
131         $cn_browse_xslt = $parser->parse_file(
132                 OpenSRF::Utils::SettingsClient
133                         ->new
134                         ->config_value( dirs => 'xsl' ).
135                 "/CNBrowse2HTML.xsl"
136         );
137
138         $cn_browse_xslt = $xslt->parse_stylesheet( $cn_browse_xslt );
139
140 }
141
142 sub oisbn {
143
144         my $apache = shift;
145         return Apache2::Const::DECLINED if (-e $apache->filename);
146
147         (my $isbn = $apache->path_info) =~ s{^.*?([^/]+)$}{$1}o;
148
149         my $list = $supercat
150                 ->request("open-ils.supercat.oisbn", $isbn)
151                 ->gather(1);
152
153         print "Content-type: application/xml; charset=utf-8\n\n";
154         print "<?xml version='1.0' encoding='UTF-8' ?>\n";
155
156         unless (exists $$list{metarecord}) {
157                 print '<idlist/>';
158                 return Apache2::Const::OK;
159         }
160
161         print "<idlist metarecord='$$list{metarecord}'>\n";
162
163         for ( keys %{ $$list{record_list} } ) {
164                 (my $o = $$list{record_list}{$_}) =~s/^(\S+).*?$/$1/o;
165                 print "  <isbn record='$_'>$o</isbn>\n"
166         }
167
168         print "</idlist>\n";
169
170         return Apache2::Const::OK;
171 }
172
173 sub unapi {
174
175         my $apache = shift;
176         return Apache2::Const::DECLINED if (-e $apache->filename);
177
178         my $cgi = new CGI;
179
180         my $add_path = 0;
181         if ( $cgi->server_software !~ m|^Apache/2.2| ) {
182                 my $rel_name = $cgi->url(-relative=>1);
183                 $add_path = 1 if ($cgi->url(-path_info=>1) !~ /$rel_name$/);
184         }
185
186         my $url = $cgi->url(-path_info=>$add_path);
187         my $root = (split 'unapi', $url)[0];
188         my $base = (split 'unapi', $url)[0] . 'unapi';
189
190
191         my $uri = $cgi->param('id') || '';
192         my $host = $cgi->virtual_host || $cgi->server_name;
193
194         my $format = $cgi->param('format');
195         my $flesh_feed = ($format =~ /-full$/o) ? 1 : 0;
196         (my $base_format = $format) =~ s/-full$//o;
197         my ($id,$type,$command,$lib) = ('','','');
198
199         if (!$format) {
200                 my $body = "Content-type: application/xml; charset=utf-8\n\n";
201         
202                 if ($uri =~ m{^tag:[^:]+:([^\/]+)/([^/]+)(?:/(.+))$}o) {
203                         $id = $2;
204                         $lib = uc($3);
205                         $type = 'record';
206                         $type = 'metarecord' if ($1 =~ /^m/o);
207
208                         my $list = $supercat
209                                 ->request("open-ils.supercat.$type.formats")
210                                 ->gather(1);
211
212                         if ($type eq 'record' or $type eq 'isbn') {
213                                 $body .= <<"                            FORMATS";
214 <formats id='$uri'>
215         <format name='opac' type='text/html'/>
216         <format name='html' type='text/html'/>
217         <format name='htmlholdings' type='text/html'/>
218         <format name='html-full' type='text/html'/>
219         <format name='htmlholdings-full' type='text/html'/>
220                                 FORMATS
221                         } elsif ($type eq 'metarecord') {
222                                 $body .= <<"                            FORMATS";
223                                 <formats id='$uri'>
224                                         <format name='opac' type='text/html'/>
225                                 FORMATS
226                         }
227
228                         for my $h (@$list) {
229                                 my ($type) = keys %$h;
230                                 $body .= "\t<format name='$type' type='application/xml'";
231
232                                 for my $part ( qw/namespace_uri docs schema_location/ ) {
233                                         $body .= " $part='$$h{$type}{$part}'"
234                                                 if ($$h{$type}{$part});
235                                 }
236                                 
237                                 $body .= "/>\n";
238
239                                 if (OpenILS::WWW::SuperCat::Feed->exists($type)) {
240                                         $body .= "\t<format name='$type-full' type='application/xml'";
241
242                                         for my $part ( qw/namespace_uri docs schema_location/ ) {
243                                                 $body .= " $part='$$h{$type}{$part}'"
244                                                         if ($$h{$type}{$part});
245                                         }
246                                 
247                                         $body .= "/>\n";
248                                 }
249                         }
250
251                         $body .= "</formats>\n";
252
253                 } else {
254                         my $list = $supercat
255                                 ->request("open-ils.supercat.record.formats")
256                                 ->gather(1);
257                                 
258                         push @$list,
259                                 @{ $supercat
260                                         ->request("open-ils.supercat.metarecord.formats")
261                                         ->gather(1);
262                                 };
263
264                         my %hash = map { ( (keys %$_)[0] => (values %$_)[0] ) } @$list;
265                         $list = [ map { { $_ => $hash{$_} } } sort keys %hash ];
266
267                         $body .= <<"                    FORMATS";
268 <formats>
269         <format name='opac' type='text/html'/>
270         <format name='html' type='text/html'/>
271         <format name='htmlholdings' type='text/html'/>
272         <format name='html-full' type='text/html'/>
273         <format name='htmlholdings-full' type='text/html'/>
274                         FORMATS
275
276
277                         for my $h (@$list) {
278                                 my ($type) = keys %$h;
279                                 $body .= "\t<format name='$type' type='application/xml'";
280
281                                 for my $part ( qw/namespace_uri docs schema_location/ ) {
282                                         $body .= " $part='$$h{$type}{$part}'"
283                                                 if ($$h{$type}{$part});
284                                 }
285                                 
286                                 $body .= "/>\n";
287
288                                 if (OpenILS::WWW::SuperCat::Feed->exists($type)) {
289                                         $body .= "\t<format name='$type-full' type='application/xml'";
290
291                                         for my $part ( qw/namespace_uri docs schema_location/ ) {
292                                                 $body .= " $part='$$h{$type}{$part}'"
293                                                         if ($$h{$type}{$part});
294                                         }
295                                 
296                                         $body .= "/>\n";
297                                 }
298                         }
299
300                         $body .= "</formats>\n";
301
302                 }
303                 print $body;
304                 return Apache2::Const::OK;
305         }
306
307         if ($uri =~ m{^tag:[^:]+:([^\/]+)/([^/]+)(?:/(.+))?}o) {
308                 $id = $2;
309                 $lib = uc($3);
310                 $type = 'record';
311                 $type = 'metarecord' if ($1 =~ /^metabib/o);
312                 $type = 'isbn' if ($1 =~ /^isbn/o);
313                 $type = 'call_number' if ($1 =~ /^call_number/o);
314                 $command = 'retrieve';
315                 $command = 'browse' if ($type eq 'call_number');
316         }
317
318         if (!$lib || $lib eq '-') {
319                 $lib = $actor->request(
320                         'open-ils.actor.org_unit_list.search' => parent_ou => undef
321                 )->gather(1)->[0]->shortname;
322         }
323
324         my $lib_object = $actor->request(
325                 'open-ils.actor.org_unit_list.search' => shortname => $lib
326         )->gather(1)->[0];
327         my $lib_id = $lib_object->id;
328
329         my $ou_types = $actor->request( 'open-ils.actor.org_types.retrieve' )->gather(1);
330         my $lib_depth = (grep { $_->id == $lib_object->ou_type } @$ou_types)[0]->depth;
331
332         if ($type eq 'call_number' and $command eq 'browse') {
333                 print "Location: $root/browse/$base_format/call_number/$lib/$id\n\n";
334                 return 302;
335         }
336
337         if ($type eq 'isbn') {
338                 my $rec = $supercat->request('open-ils.supercat.isbn.object.retrieve',$id)->gather(1);
339                 if (!@$rec) {
340                         print "Content-type: text/html; charset=utf-8\n\n";
341                         $apache->custom_response( 404, <<"                      HTML");
342                         <html>
343                                 <head>
344                                         <title>Type [$type] with id [$id] not found!</title>
345                                 </head>
346                                 <body>
347                                         <br/>
348                                         <center>Sorry, we couldn't $command a $type with the id of $id in format $format.</center>
349                                 </body>
350                         </html>
351                         HTML
352                         return 404;
353                 }
354                 $id = $rec->[0]->id;
355                 $type = 'record';
356         }
357
358         if ( !grep
359                { (keys(%$_))[0] eq $base_format }
360                @{ $supercat->request("open-ils.supercat.$type.formats")->gather(1) }
361              and !grep
362                { $_ eq $base_format }
363                qw/opac html htmlholdings/
364         ) {
365                 print "Content-type: text/html; charset=utf-8\n\n";
366                 $apache->custom_response( 406, <<"              HTML");
367                 <html>
368                         <head>
369                                 <title>Invalid format [$format] for type [$type]!</title>
370                         </head>
371                         <body>
372                                 <br/>
373                                 <center>Sorry, format $format is not valid for type $type.</center>
374                         </body>
375                 </html>
376                 HTML
377                 return 406;
378         }
379
380         if ($format eq 'opac') {
381                 print "Location: $root/../../en-US/skin/default/xml/rresult.xml?m=$id&l=$lib_id&d=$lib_depth\n\n"
382                         if ($type eq 'metarecord');
383                 print "Location: $root/../../en-US/skin/default/xml/rdetail.xml?r=$id&l=$lib_id&d=$lib_depth\n\n"
384                         if ($type eq 'record');
385                 return 302;
386         } elsif (OpenILS::WWW::SuperCat::Feed->exists($base_format)) {
387                 my $feed = create_record_feed(
388                         $type,
389                         $format => [ $id ],
390                         $base,
391                         $lib,
392                         $flesh_feed
393                 );
394
395                 if (!$feed->count) {
396                         print "Content-type: text/html; charset=utf-8\n\n";
397                         $apache->custom_response( 404, <<"                      HTML");
398                         <html>
399                                 <head>
400                                         <title>Type [$type] with id [$id] not found!</title>
401                                 </head>
402                                 <body>
403                                         <br/>
404                                         <center>Sorry, we couldn't $command a $type with the id of $id in format $format.</center>
405                                 </body>
406                         </html>
407                         HTML
408                         return 404;
409                 }
410
411                 $feed->root($root);
412                 $feed->creator($host);
413                 $feed->update_ts(gmtime_ISO8601());
414                 $feed->link( unapi => $base) if ($flesh_feed);
415
416                 print "Content-type: ". $feed->type ."; charset=utf-8\n\n";
417                 print entityize($feed->toString) . "\n";
418
419                 return Apache2::Const::OK;
420         }
421
422         my $req = $supercat->request("open-ils.supercat.$type.$format.$command",$id);
423         my $data = $req->gather(1);
424
425         if ($req->failed || !$data) {
426                 print "Content-type: text/html; charset=utf-8\n\n";
427                 $apache->custom_response( 404, <<"              HTML");
428                 <html>
429                         <head>
430                                 <title>$type $id not found!</title>
431                         </head>
432                         <body>
433                                 <br/>
434                                 <center>Sorry, we couldn't $command a $type with the id of $id in format $format.</center>
435                         </body>
436                 </html>
437                 HTML
438                 return 404;
439         }
440
441         print "Content-type: application/xml; charset=utf-8\n\n$data";
442
443         return Apache2::Const::OK;
444 }
445
446 sub supercat {
447
448         my $apache = shift;
449         return Apache2::Const::DECLINED if (-e $apache->filename);
450
451         my $cgi = new CGI;
452
453         my $add_path = 0;
454         if ( $cgi->server_software !~ m|^Apache/2.2| ) {
455                 my $rel_name = $cgi->url(-relative=>1);
456                 $add_path = 1 if ($cgi->url(-path_info=>1) !~ /$rel_name$/);
457         }
458
459         my $url = $cgi->url(-path_info=>$add_path);
460         my $root = (split 'supercat', $url)[0];
461         my $base = (split 'supercat', $url)[0] . 'supercat';
462         my $unapi = (split 'supercat', $url)[0] . 'unapi';
463
464         my $host = $cgi->virtual_host || $cgi->server_name;
465
466         my $path = $cgi->path_info;
467         my ($id,$type,$format,$command) = reverse split '/', $path;
468         my $flesh_feed = ($type =~ /-full$/o) ? 1 : 0;
469         (my $base_format = $format) =~ s/-full$//o;
470         
471         if ( $path =~ m{^/formats(?:/([^\/]+))?$}o ) {
472                 print "Content-type: application/xml; charset=utf-8\n";
473                 if ($1) {
474                         my $list = $supercat
475                                 ->request("open-ils.supercat.$1.formats")
476                                 ->gather(1);
477
478                         print "\n";
479
480                         print "<formats>
481                                    <format>
482                                      <name>opac</name>
483                                      <type>text/html</type>
484                                    </format>";
485
486                         if ($1 eq 'record' or $1 eq 'isbn') {
487                                 print "<format>
488                                      <name>htmlholdings</name>
489                                      <type>text/html</type>
490                                    </format>
491                                    <format>
492                                      <name>html</name>
493                                      <type>text/html</type>
494                                    </format>
495                                    <format>
496                                      <name>htmlholdings-full</name>
497                                      <type>text/html</type>
498                                    </format>
499                                    <format>
500                                      <name>html-full</name>
501                                      <type>text/html</type>
502                                    </format>";
503                         }
504
505                         for my $h (@$list) {
506                                 my ($type) = keys %$h;
507                                 print "<format><name>$type</name><type>application/xml</type>";
508
509                                 for my $part ( qw/namespace_uri docs schema_location/ ) {
510                                         print "<$part>$$h{$type}{$part}</$part>"
511                                                 if ($$h{$type}{$part});
512                                 }
513                                 
514                                 print '</format>';
515
516                                 if (OpenILS::WWW::SuperCat::Feed->exists($type)) {
517                                         print "<format><name>$type-full</name><type>application/xml</type>";
518
519                                         for my $part ( qw/namespace_uri docs schema_location/ ) {
520                                                 print "<$part>$$h{$type}{$part}</$part>"
521                                                         if ($$h{$type}{$part});
522                                         }
523                                 
524                                         print '</format>';
525                                 }
526
527                         }
528
529                         print "</formats>\n";
530
531                         return Apache2::Const::OK;
532                 }
533
534                 my $list = $supercat
535                         ->request("open-ils.supercat.record.formats")
536                         ->gather(1);
537                                 
538                 push @$list,
539                         @{ $supercat
540                                 ->request("open-ils.supercat.metarecord.formats")
541                                 ->gather(1);
542                         };
543
544                 my %hash = map { ( (keys %$_)[0] => (values %$_)[0] ) } @$list;
545                 $list = [ map { { $_ => $hash{$_} } } sort keys %hash ];
546
547                 print "\n<formats>
548                            <format>
549                              <name>opac</name>
550                              <type>text/html</type>
551                            </format>
552                            <format>
553                              <name>htmlholdings</name>
554                              <type>text/html</type>
555                            </format>
556                            <format>
557                              <name>html</name>
558                              <type>text/html</type>
559                            </format>
560                            <format>
561                              <name>htmlholdings-full</name>
562                              <type>text/html</type>
563                            </format>
564                            <format>
565                              <name>html-full</name>
566                              <type>text/html</type>
567                            </format>";
568
569                 for my $h (@$list) {
570                         my ($type) = keys %$h;
571                         print "<format><name>$type</name><type>application/xml</type>";
572
573                         for my $part ( qw/namespace_uri docs schema_location/ ) {
574                                 print "<$part>$$h{$type}{$part}</$part>"
575                                         if ($$h{$type}{$part});
576                         }
577                         
578                         print '</format>';
579
580                         if (OpenILS::WWW::SuperCat::Feed->exists($type)) {
581                                 print "<format><name>$type-full</name><type>application/xml</type>";
582
583                                 for my $part ( qw/namespace_uri docs schema_location/ ) {
584                                         print "<$part>$$h{$type}{$part}</$part>"
585                                                 if ($$h{$type}{$part});
586                                 }
587                                 
588                                 print '</format>';
589                         }
590
591                 }
592
593                 print "</formats>\n";
594
595
596                 return Apache2::Const::OK;
597         }
598
599         if ($format eq 'opac') {
600                 print "Location: $root/../../en-US/skin/default/xml/rresult.xml?m=$id\n\n"
601                         if ($type eq 'metarecord');
602                 print "Location: $root/../../en-US/skin/default/xml/rdetail.xml?r=$id\n\n"
603                         if ($type eq 'record');
604                 return 302;
605
606         } elsif ($base_format eq 'marc21') {
607
608                 my $ret = 200;    
609                 try {
610                         my $bib = $supercat->request( "open-ils.supercat.record.object.retrieve", $id )->gather(1)->[0];
611         
612                         my $r = MARC::Record->new_from_xml( $bib->marc, 'UTF-8', 'USMARC' );
613                         $r->delete_field( $_ ) for ($r->field(901));
614                 
615                         $r->append_fields(
616                                 MARC::Field->new(
617                                         901, '', '',
618                                         a => $bib->tcn_value,
619                                         b => $bib->tcn_source,
620                                         c => $bib->id
621                                 )
622                         );
623
624                         print "Content-type: application/octet-stream\n\n";
625                         print $r->as_usmarc;
626
627                 } otherwise {
628                         warn shift();
629                         
630                         print "Content-type: text/html; charset=utf-8\n\n";
631                         $apache->custom_response( 404, <<"                      HTML");
632                         <html>
633                                 <head>
634                                         <title>ERROR</title>
635                                 </head>
636                                 <body>
637                                         <br/>
638                                         <center>Couldn't fetch $id as MARC21.</center>
639                                 </body>
640                         </html>
641                         HTML
642                         $ret = 404;
643                 };
644
645                 return Apache2::Const::OK;
646
647         } elsif (OpenILS::WWW::SuperCat::Feed->exists($base_format)) {
648                 my $feed = create_record_feed(
649                         $type,
650                         $format => [ $id ],
651                         undef, undef,
652                         $flesh_feed
653                 );
654
655                 $feed->root($root);
656                 $feed->creator($host);
657                 $feed->update_ts(gmtime_ISO8601());
658                 $feed->link( unapi => $base) if ($flesh_feed);
659
660                 print "Content-type: ". $feed->type ."; charset=utf-8\n\n";
661                 print entityize($feed->toString) . "\n";
662
663                 return Apache2::Const::OK;
664         }
665
666         my $req = $supercat->request("open-ils.supercat.$type.$format.$command",$id);
667         $req->wait_complete;
668
669         if ($req->failed) {
670                 print "Content-type: text/html; charset=utf-8\n\n";
671                 $apache->custom_response( 404, <<"              HTML");
672                 <html>
673                         <head>
674                                 <title>$type $id not found!</title>
675                         </head>
676                         <body>
677                                 <br/>
678                                 <center>Sorry, we couldn't $command a $type with the id of $id in format $format.</center>
679                         </body>
680                 </html>
681                 HTML
682                 return 404;
683         }
684
685         print "Content-type: application/xml; charset=utf-8\n\n";
686         print entityize( $parser->parse_string( $req->gather(1) )->documentElement->toString );
687
688         return Apache2::Const::OK;
689 }
690
691
692 sub bookbag_feed {
693         my $apache = shift;
694         return Apache2::Const::DECLINED if (-e $apache->filename);
695
696         my $cgi = new CGI;
697
698         my $year = (gmtime())[5] + 1900;
699         my $host = $cgi->virtual_host || $cgi->server_name;
700
701         my $add_path = 0;
702         if ( $cgi->server_software !~ m|^Apache/2.2| ) {
703                 my $rel_name = $cgi->url(-relative=>1);
704                 $add_path = 1 if ($cgi->url(-path_info=>1) !~ /$rel_name$/);
705         }
706
707         my $url = $cgi->url(-path_info=>$add_path);
708         my $root = (split 'feed', $url)[0] . '/';
709         my $base = (split 'bookbag', $url)[0] . '/bookbag';
710         my $unapi = (split 'feed', $url)[0] . '/unapi';
711
712         $root =~ s{(?<!http:)//}{/}go;
713         $base =~ s{(?<!http:)//}{/}go;
714         $unapi =~ s{(?<!http:)//}{/}go;
715
716         my $path = $cgi->path_info;
717         #warn "URL breakdown: $url -> $root -> $base -> $path -> $unapi";
718
719         my ($id,$type) = reverse split '/', $path;
720         my $flesh_feed = ($type =~ /-full$/o) ? 1 : 0;
721
722         my $bucket = $actor->request("open-ils.actor.container.public.flesh", 'biblio', $id)->gather(1);
723         return Apache2::Const::NOT_FOUND unless($bucket);
724
725         my $bucket_tag = "tag:$host,$year:record_bucket/$id";
726         if ($type eq 'opac') {
727                 print "Location: $root/../../en-US/skin/default/xml/rresult.xml?rt=list&" .
728                         join('&', map { "rl=" . $_->target_biblio_record_entry } @{ $bucket->items }) .
729                         "\n\n";
730                 return 302;
731         }
732
733         my $feed = create_record_feed(
734                 'record',
735                 $type,
736                 [ map { $_->target_biblio_record_entry } @{ $bucket->items } ],
737                 $unapi,
738                 undef,
739                 $flesh_feed
740         );
741         $feed->root($root);
742
743         $feed->title("Items in Book Bag [".$bucket->name."]");
744         $feed->creator($host);
745         $feed->update_ts(gmtime_ISO8601());
746
747         $feed->link(rss => $base . "/rss2-full/$id" => 'application/rss+xml');
748         $feed->link(alternate => $base . "/atom-full/$id" => 'application/atom+xml');
749         $feed->link(html => $base . "/html-full/$id" => 'text/html');
750         $feed->link(unapi => $unapi);
751
752         $feed->link(
753                 OPAC =>
754                 '/opac/en-US/skin/default/xml/rresult.xml?rt=list&' .
755                         join('&', map { 'rl=' . $_->target_biblio_record_entry } @{$bucket->items} ),
756                 'text/html'
757         );
758
759
760         print "Content-type: ". $feed->type ."; charset=utf-8\n\n";
761         print entityize($feed->toString) . "\n";
762
763         return Apache2::Const::OK;
764 }
765
766 sub changes_feed {
767         my $apache = shift;
768         return Apache2::Const::DECLINED if (-e $apache->filename);
769
770         my $cgi = new CGI;
771
772         my $year = (gmtime())[5] + 1900;
773         my $host = $cgi->virtual_host || $cgi->server_name;
774
775         my $add_path = 0;
776         if ( $cgi->server_software !~ m|^Apache/2.2| ) {
777                 my $rel_name = $cgi->url(-relative=>1);
778                 $add_path = 1 if ($cgi->url(-path_info=>1) !~ /$rel_name$/);
779         }
780
781         my $url = $cgi->url(-path_info=>$add_path);
782         my $root = (split 'feed', $url)[0];
783         my $base = (split 'freshmeat', $url)[0] . 'freshmeat';
784         my $unapi = (split 'feed', $url)[0] . 'unapi';
785
786         my $path = $cgi->path_info;
787         #warn "URL breakdown: $url ($rel_name) -> $root -> $base -> $path -> $unapi";
788
789         $path =~ s/^\/(?:feed\/)?freshmeat\///og;
790         
791         my ($type,$rtype,$axis,$limit,$date) = split '/', $path;
792         my $flesh_feed = ($type =~ /-full$/o) ? 1 : 0;
793         $limit ||= 10;
794
795         my $list = $supercat->request("open-ils.supercat.$rtype.record.$axis.recent", $date, $limit)->gather(1);
796
797         #if ($type eq 'opac') {
798         #       print "Location: $root/../../en-US/skin/default/xml/rresult.xml?rt=list&" .
799         #               join('&', map { "rl=" . $_ } @$list) .
800         #               "\n\n";
801         #       return 302;
802         #}
803
804         my $feed = create_record_feed( 'record', $type, $list, $unapi, undef, $flesh_feed);
805         $feed->root($root);
806
807         if ($date) {
808                 $feed->title("Up to $limit recent $rtype ${axis}s from $date forward");
809         } else {
810                 $feed->title("$limit most recent $rtype ${axis}s");
811         }
812
813         $feed->creator($host);
814         $feed->update_ts(gmtime_ISO8601());
815
816         $feed->link(rss => $base . "/rss2-full/$rtype/$axis/$limit/$date" => 'application/rss+xml');
817         $feed->link(alternate => $base . "/atom-full/$rtype/$axis/$limit/$date" => 'application/atom+xml');
818         $feed->link(html => $base . "/html-full/$rtype/$axis/$limit/$date" => 'text/html');
819         $feed->link(unapi => $unapi);
820
821         $feed->link(
822                 OPAC =>
823                 '/opac/en-US/skin/default/xml/rresult.xml?rt=list&' .
824                         join('&', map { 'rl=' . $_} @$list ),
825                 'text/html'
826         );
827
828
829         print "Content-type: ". $feed->type ."; charset=utf-8\n\n";
830         print entityize($feed->toString) . "\n";
831
832         return Apache2::Const::OK;
833 }
834
835 sub opensearch_osd {
836         my $version = shift;
837         my $lib = shift;
838         my $class = shift;
839         my $base = shift;
840
841         if ($version eq '1.0') {
842                 print <<OSD;
843 Content-type: application/opensearchdescription+xml; charset=utf-8
844
845 <?xml version="1.0" encoding="UTF-8"?>
846 <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearchdescription/1.0/">
847   <Url>$base/1.0/$lib/-/$class/?searchTerms={searchTerms}&amp;startPage={startPage}&amp;startIndex={startIndex}&amp;count={count}</Url>
848   <Format>http://a9.com/-/spec/opensearchrss/1.0/</Format>
849   <ShortName>$lib</ShortName>
850   <LongName>Search $lib</LongName>
851   <Description>Search the $lib OPAC by $class.</Description>
852   <Tags>$lib book library</Tags>
853   <SampleSearch>harry+potter</SampleSearch>
854   <Developer>Mike Rylander for GPLS/PINES</Developer>
855   <Contact>feedback\@open-ils.org</Contact>
856   <SyndicationRight>open</SyndicationRight>
857   <AdultContent>false</AdultContent>
858 </OpenSearchDescription>
859 OSD
860         } else {
861                 print <<OSD;
862 Content-type: application/opensearchdescription+xml; charset=utf-8
863
864 <?xml version="1.0" encoding="UTF-8"?>
865 <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">
866   <ShortName>$lib</ShortName>
867   <Description>Search the $lib OPAC by $class.</Description>
868   <Tags>$lib book library</Tags>
869   <Url type="application/rss+xml"
870        template="$base/1.1/$lib/rss2-full/$class/?searchTerms={searchTerms}&amp;startPage={startPage?}&amp;startIndex={startIndex?}&amp;count={count?}&amp;searchLang={language?}"/>
871   <Url type="application/atom+xml"
872        template="$base/1.1/$lib/atom-full/$class/?searchTerms={searchTerms}&amp;startPage={startPage?}&amp;startIndex={startIndex?}&amp;count={count?}&amp;searchLang={language?}"/>
873   <Url type="application/x-mods3+xml"
874        template="$base/1.1/$lib/mods3/$class/?searchTerms={searchTerms}&amp;startPage={startPage?}&amp;startIndex={startIndex?}&amp;count={count?}&amp;searchLang={language?}"/>
875   <Url type="application/x-mods+xml"
876        template="$base/1.1/$lib/mods/$class/?searchTerms={searchTerms}&amp;startPage={startPage?}&amp;startIndex={startIndex?}&amp;count={count?}&amp;searchLang={language?}"/>
877   <Url type="application/x-marcxml+xml"
878        template="$base/1.1/$lib/marcxml/$class/?searchTerms={searchTerms}&amp;startPage={startPage?}&amp;startIndex={startIndex?}&amp;count={count?}&amp;searchLang={language?}"/>
879   <Url type="text/html"
880        template="$base/1.1/$lib/html-full/$class/?searchTerms={searchTerms}&amp;startPage={startPage?}&amp;startIndex={startIndex?}&amp;count={count?}&amp;searchLang={language?}"/>
881   <LongName>Search $lib</LongName>
882   <Query role="example" searchTerms="harry+potter" />
883   <Developer>Mike Rylander for GPLS/PINES</Developer>
884   <Contact>feedback\@open-ils.org</Contact>
885   <SyndicationRight>open</SyndicationRight>
886   <AdultContent>false</AdultContent>
887   <Language>en-US</Language>
888   <OutputEncoding>UTF-8</OutputEncoding>
889   <InputEncoding>UTF-8</InputEncoding>
890 </OpenSearchDescription>
891 OSD
892         }
893
894         return Apache2::Const::OK;
895 }
896
897 sub opensearch_feed {
898         my $apache = shift;
899         return Apache2::Const::DECLINED if (-e $apache->filename);
900
901         my $cgi = new CGI;
902         my $year = (gmtime())[5] + 1900;
903
904         my $host = $cgi->virtual_host || $cgi->server_name;
905
906         my $add_path = 0;
907         if ( $cgi->server_software !~ m|^Apache/2.2| ) {
908                 my $rel_name = $cgi->url(-relative=>1);
909                 $add_path = 1 if ($cgi->url(-path_info=>1) !~ /$rel_name$/);
910         }
911
912         my $url = $cgi->url(-path_info=>$add_path);
913         my $root = (split 'opensearch', $url)[0];
914         my $base = (split 'opensearch', $url)[0] . 'opensearch';
915         my $unapi = (split 'opensearch', $url)[0] . 'unapi';
916
917         my $path = $cgi->path_info;
918         #warn "URL breakdown: $url ($rel_name) -> $root -> $base -> $path -> $unapi";
919
920         if ($path =~ m{^/?(1\.\d{1})/(?:([^/]+)/)?([^/]+)/osd.xml}o) {
921                 
922                 my $version = $1;
923                 my $lib = uc($2);
924                 my $class = $3;
925
926                 if (!$lib || $lib eq '-') {
927                         $lib = $actor->request(
928                                 'open-ils.actor.org_unit_list.search' => parent_ou => undef
929                         )->gather(1)->[0]->shortname;
930                 }
931
932                 if ($class eq '-') {
933                         $class = 'keyword';
934                 }
935
936                 return opensearch_osd($version, $lib, $class, $base);
937         }
938
939
940         my $page = $cgi->param('startPage') || 1;
941         my $offset = $cgi->param('startIndex') || 1;
942         my $limit = $cgi->param('count') || 10;
943
944         $page = 1 if ($page !~ /^\d+$/);
945         $offset = 1 if ($offset !~ /^\d+$/);
946         $limit = 10 if ($limit !~ /^\d+$/); $limit = 25 if ($limit > 25);
947
948         if ($page > 1) {
949                 $offset = ($page - 1) * $limit;
950         } else {
951                 $offset -= 1;
952         }
953
954         my ($version,$org,$type,$class,$terms,$sort,$sortdir,$lang) = ('','','','','','','','');
955         (undef,$version,$org,$type,$class,$terms,$sort,$sortdir,$lang) = split '/', $path;
956
957         $lang = $cgi->param('searchLang') if $cgi->param('searchLang');
958         $lang = '' if ($lang eq '*');
959
960         $sort = $cgi->param('searchSort') if $cgi->param('searchSort');
961         $sortdir = $cgi->param('searchSortDir') if $cgi->param('searchSortDir');
962         $terms .= " " . $cgi->param('searchTerms') if $cgi->param('searchTerms');
963
964         $class = $cgi->param('searchClass') if $cgi->param('searchClass');
965         $class ||= '-';
966
967         $type = $cgi->param('responseType') if $cgi->param('responseType');
968         $type ||= '-';
969
970         $org = $cgi->param('searchOrg') if $cgi->param('searchOrg');
971         $org ||= '-';
972
973
974         my $kwt = $cgi->param('kw');
975         my $tit = $cgi->param('ti');
976         my $aut = $cgi->param('au');
977         my $sut = $cgi->param('su');
978         my $set = $cgi->param('se');
979
980         $terms .= " keyword: $kwt" if ($kwt);
981         $terms .= " title: $tit" if ($tit);
982         $terms .= " author: $aut" if ($aut);
983         $terms .= " subject: $sut" if ($sut);
984         $terms .= " series: $set" if ($set);
985
986         if ($version eq '1.0') {
987                 $type = 'rss2';
988         } elsif ($type eq '-') {
989                 $type = 'atom';
990         }
991         my $flesh_feed = ($type =~ /-full$/o) ? 1 : 0;
992
993         if ($terms eq 'help') {
994                 print $cgi->header(-type => 'text/html');
995                 print <<"               HTML";
996                         <html>
997                          <head>
998                           <title>just type something!</title>
999                          </head>
1000                          <body>
1001                           <p>You are in a maze of dark, twisty stacks, all alike.</p>
1002                          </body>
1003                         </html>
1004                 HTML
1005                 return Apache2::Const::OK;
1006     }
1007         
1008         $terms = decode_utf8($terms);
1009         $lang = 'eng' if ($lang eq 'en-US');
1010
1011         my $org_unit;
1012         if ($org eq '-') {
1013                 $org_unit = $actor->request(
1014                         'open-ils.actor.org_unit_list.search' => parent_ou => undef
1015                 )->gather(1);
1016         } else {
1017                 $org_unit = $actor->request(
1018                         'open-ils.actor.org_unit_list.search' => shortname => uc($org)
1019                 )->gather(1);
1020         }
1021
1022     my $recs = $search->request(
1023         'open-ils.search.biblio.multiclass.query' => {
1024                         org_unit        => $org_unit->[0]->id,
1025                         offset          => $limit,
1026                         limit           => $offset,
1027                         ($lang ?    ( 'language' => $lang    ) : ()),
1028                 } => $terms
1029         )->gather(1);
1030
1031         my $feed = create_record_feed(
1032                 'record',
1033                 $type,
1034                 [ map { $_->[0] } @{$recs->{ids}} ],
1035                 $unapi,
1036                 $org,
1037                 $flesh_feed
1038         );
1039         $feed->root($root);
1040         $feed->lib($org);
1041         $feed->search($terms);
1042         $feed->class($class);
1043
1044         if ($complex_terms) {
1045                 $feed->title("Search results for [$terms] at ".$org_unit->[0]->name);
1046         } else {
1047                 $feed->title("Search results for [$class => $terms] at ".$org_unit->[0]->name);
1048         }
1049
1050         $feed->creator($host);
1051         $feed->update_ts(gmtime_ISO8601());
1052
1053         $feed->_create_node(
1054                 $feed->{item_xpath},
1055                 'http://a9.com/-/spec/opensearch/1.1/',
1056                 'totalResults',
1057                 $recs->{count},
1058         );
1059
1060         $feed->_create_node(
1061                 $feed->{item_xpath},
1062                 'http://a9.com/-/spec/opensearch/1.1/',
1063                 'startIndex',
1064                 $offset + 1,
1065         );
1066
1067         $feed->_create_node(
1068                 $feed->{item_xpath},
1069                 'http://a9.com/-/spec/opensearch/1.1/',
1070                 'itemsPerPage',
1071                 $limit,
1072         );
1073
1074         $feed->link(
1075                 next =>
1076                 $base . "/$version/$org/$type/$class?searchTerms=$terms&searchSort=$sort&searchSortDir=$sortdir&searchLang=$lang&startIndex=" . int($offset + $limit + 1) . "&count=" . $limit =>
1077                 'application/opensearch+xml'
1078         ) if ($offset + $limit < $recs->{count});
1079
1080         $feed->link(
1081                 previous =>
1082                 $base . "/$version/$org/$type/$class?searchTerms=$terms&searchSort=$sort&searchSortDir=$sortdir&searchLang=$lang&startIndex=" . int(($offset - $limit) + 1) . "&count=" . $limit =>
1083                 'application/opensearch+xml'
1084         ) if ($offset);
1085
1086         $feed->link(
1087                 self =>
1088                 $base .  "/$version/$org/$type/$class?searchTerms=$terms&searchSort=$sort&searchSortDir=$sortdir&searchLang=$lang" =>
1089                 'application/opensearch+xml'
1090         );
1091
1092         $feed->link(
1093                 rss =>
1094                 $base .  "/$version/$org/rss2-full/$class?searchTerms=$terms&searchSort=$sort&searchSortDir=$sortdir&searchLang=$lang" =>
1095                 'application/rss+xml'
1096         );
1097
1098         $feed->link(
1099                 alternate =>
1100                 $base .  "/$version/$org/atom-full/$class?searchTerms=$terms&searchSort=$sort&searchSortDir=$sortdir&searchLang=$lang" =>
1101                 'application/atom+xml'
1102         );
1103
1104         $feed->link(
1105                 'html' =>
1106                 $base .  "/$version/$org/html/$class?searchTerms=$terms&searchSort=$sort&searchSortDir=$sortdir&searchLang=$lang" =>
1107                 'text/html'
1108         );
1109
1110         $feed->link(
1111                 'html-full' =>
1112                 $base .  "/$version/$org/html-full/$class?searchTerms=$terms&searchSort=$sort&searchSortDir=$sortdir&searchLang=$lang" =>
1113                 'text/html'
1114         );
1115
1116         $feed->link( 'unapi-server' => $unapi);
1117
1118 #       $feed->link(
1119 #               opac =>
1120 #               $root . "../$lang/skin/default/xml/rresult.xml?rt=list&" .
1121 #                       join('&', map { 'rl=' . $_->[0] } grep { ref $_ && defined $_->[0] } @{$recs->{ids}} ),
1122 #               'text/html'
1123 #       );
1124
1125         print $cgi->header(
1126                 -type           => $feed->type,
1127                 -charset        => 'UTF-8',
1128                 -cookie         => $cgi->cookie( -name => 'os_session', -value => $rs_name, -expires => '+30m' ),
1129         );
1130
1131         print entityize($feed->toString) . "\n";
1132
1133         return Apache2::Const::OK;
1134 }
1135
1136 sub create_record_feed {
1137         my $search = shift;
1138         my $type = shift;
1139         my $records = shift;
1140         my $unapi = shift;
1141
1142         my $lib = uc(shift()) || '-';
1143         my $flesh = shift;
1144         $flesh = 1 if (!defined($flesh));
1145
1146         my $cgi = new CGI;
1147         my $base = $cgi->url;
1148         my $host = $cgi->virtual_host || $cgi->server_name;
1149
1150         my $year = (gmtime())[5] + 1900;
1151
1152         my $flesh_feed = ($type =~ s/-full$//o) ? 1 : 0;
1153
1154         my $feed = new OpenILS::WWW::SuperCat::Feed ($type);
1155         $feed->base($base) if ($flesh);
1156         $feed->unapi($unapi) if ($flesh);
1157
1158         $type = 'atom' if ($type eq 'html');
1159         $type = 'marcxml' if ($type eq 'htmlholdings');
1160
1161         #$records = $supercat->request( "open-ils.supercat.record.object.retrieve", $records )->gather(1);
1162
1163         my $count = 0;
1164         for my $record (@$records) {
1165                 next unless($record);
1166
1167                 #my $rec = $record->id;
1168                 my $rec = $record;
1169
1170                 my $item_tag = "tag:$host,$year:biblio-record_entry/$rec/$lib";
1171                 $item_tag = "tag:$host,$year:isbn/$rec/$lib" if ($search eq 'isbn');
1172
1173                 my $xml = $supercat->request(
1174                         "open-ils.supercat.$search.$type.retrieve",
1175                         $rec
1176                 )->gather(1);
1177                 next unless $xml;
1178
1179                 my $node = $feed->add_item($xml);
1180                 next unless $node;
1181
1182                 $xml = '';
1183                 if ($lib && $type eq 'marcxml' &&  $flesh) {
1184                         my $r = $supercat->request( "open-ils.supercat.$search.holdings_xml.retrieve", $rec, $lib );
1185                         while ( !$r->complete ) {
1186                                 $xml .= join('', map {$_->content} $r->recv);
1187                         }
1188                         $xml .= join('', map {$_->content} $r->recv);
1189                         $node->add_holdings($xml);
1190                 }
1191
1192                 $node->id($item_tag) if ($flesh);
1193                 #$node->update_ts(clense_ISO8601($record->edit_date));
1194                 $node->link(alternate => $feed->unapi . "?id=$item_tag&format=htmlholdings-full" => 'text/html') if ($flesh);
1195                 $node->link(opac => $feed->unapi . "?id=$item_tag&format=opac") if ($flesh);
1196                 $node->link(unapi => $feed->unapi . "?id=$item_tag") if ($flesh);
1197                 $node->link('unapi-id' => $item_tag) if ($flesh);
1198         }
1199
1200         return $feed;
1201 }
1202
1203 sub entityize {
1204         my $stuff = NFC(shift());
1205         $stuff =~ s/&(?!\S+;)/&amp;/gso;
1206         $stuff =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
1207         return $stuff;
1208 }
1209
1210 sub string_browse {
1211         my $apache = shift;
1212         return Apache2::Const::DECLINED if (-e $apache->filename);
1213
1214         my $cgi = new CGI;
1215         my $year = (gmtime())[5] + 1900;
1216
1217         my $host = $cgi->virtual_host || $cgi->server_name;
1218
1219         my $add_path = 0;
1220         if ( $cgi->server_software !~ m|^Apache/2.2| ) {
1221                 my $rel_name = $cgi->url(-relative=>1);
1222                 $add_path = 1 if ($cgi->url(-path_info=>1) !~ /$rel_name$/);
1223         }
1224
1225         my $url = $cgi->url(-path_info=>$add_path);
1226         my $root = (split 'browse', $url)[0];
1227         my $base = (split 'browse', $url)[0] . 'browse';
1228         my $unapi = (split 'browse', $url)[0] . 'unapi';
1229
1230         my $path = $cgi->path_info;
1231         $path =~ s/^\///og;
1232
1233         my ($format,$axis,$site,$string,$page,$page_size) = split '/', $path;
1234         #warn " >>> $format -> $axis -> $site -> $string -> $page -> $page_size ";
1235
1236         $site ||= $cgi->param('searchOrg');
1237         $page ||= $cgi->param('startPage') || 0;
1238         $page_size ||= $cgi->param('count') || 9;
1239
1240         $page = 0 if ($page !~ /^-?\d+$/);
1241
1242         my $prev = join('/', $base,$format,$axis,$site,$string,$page - 1,$page_size);
1243         my $next = join('/', $base,$format,$axis,$site,$string,$page + 1,$page_size);
1244
1245         unless ($string and $axis and grep { $axis eq $_ } keys %browse_types) {
1246                 warn "something's wrong...";
1247                 warn " >>> $format -> $axis -> $site -> $string -> $page -> $page_size ";
1248                 return undef;
1249         }
1250
1251         $string = decode_utf8($string);
1252         $string =~ s/\+/ /go;
1253         $string =~ s/'//go;
1254
1255         my $tree = $supercat->request(
1256                 "open-ils.supercat.$axis.browse",
1257                 $string,
1258                 $site,
1259                 $page_size,
1260                 $page
1261         )->gather(1);
1262
1263         my ($header,$content) = $browse_types{$axis}{$format}->($tree,$prev,$next);
1264         print $header.$content;
1265         return Apache2::Const::OK;
1266 }
1267
1268 sub sru_search {
1269     my $cgi = new CGI;
1270
1271     my $req = SRU::Request->newFromCGI( $cgi );
1272     my $resp = SRU::Response->newFromRequest( $req );
1273
1274     if ( $resp->type eq 'searchRetrieve' ) {
1275                 my $cql_query = $req->query;
1276                 my $search_string = $req->cql->toEvergreen;
1277
1278         my $offset = $req->startRecord;
1279         $offset-- if ($offset);
1280         $offset ||= 0;
1281
1282         my $limit = $req->maximumRecords;
1283         $limit ||= 10;
1284
1285         warn "SRU search string [$cql_query] converted to [$search_string]\n";
1286
1287                 my $recs = $search->request(
1288                         'open-ils.search.biblio.multiclass.query' => {offset => $offset, limit => $limit} => $search_string
1289                 )->gather(1);
1290
1291         my $bre = $supercat->request( 'open-ils.supercat.record.object.retrieve' => [ map { $_->[0] } @{$recs->{ids}} ] )->gather(1);
1292
1293         $resp->addRecord(
1294             SRU::Response::Record->new(
1295                 recordSchema    => 'info:srw/schema/1/marcxml-v1.1',
1296                 recordData => $_->marc
1297             )
1298         ) for @$bre;
1299
1300         $resp->numberOfRecords($recs->{count});
1301
1302         print $cgi->header( -type => 'application/xml' );
1303         print entityize($resp->asXML) . "\n";
1304             return Apache2::Const::OK;
1305     }
1306 }
1307
1308 {
1309     package CQL::BooleanNode;
1310
1311     sub toEvergreen {
1312         my $self     = shift;
1313         my $left     = $self->left();
1314         my $right    = $self->right();
1315         my $leftStr  = $left->toEvergreen;
1316         my $rightStr = $right->toEvergreen();
1317
1318         my $op =  '||' if uc $self->op() eq 'OR';
1319         $op ||=  '&&';
1320
1321         return  "$leftStr $rightStr";
1322     }
1323
1324     package CQL::TermNode;
1325
1326     our %qualifier_map = (
1327
1328         # Som EG qualifiers
1329         'eg.site'               => 'site',
1330         'eg.sort'               => 'sort',
1331         'eg.direction'          => 'dir',
1332         'eg.available'          => 'available',
1333
1334         # Title class:
1335         'dc.title'              => 'title',
1336         'bib.titleabbreviated'  => 'title|abbreviated',
1337         'bib.titleuniform'      => 'title|uniform',
1338         'bib.titletranslated'   => 'title|translated',
1339         'bib.titlealternative'  => 'title',
1340         'bib.titleseries'       => 'series',
1341
1342         # Author/Name class:
1343         'creator'               => 'author',
1344         'dc.creator'            => 'author',
1345         'dc.contributer'        => 'author',
1346         'dc.publisher'          => 'keyword',
1347         'bib.name'              => 'author',
1348         'bib.namepersonal'      => 'author|personal',
1349         'bib.namepersonalfamily'=> 'author|personal',
1350         'bib.namepersonalgiven' => 'author|personal',
1351         'bib.namecorporate'     => 'author|corporate',
1352         'bib.nameconference'    => 'author|converence',
1353
1354         # Subject class:
1355         'dc.subject'            => 'subject',
1356         'bib.subjectplace'      => 'subject|geographic',
1357         'bib.subjecttitle'      => 'keyword',
1358         'bib.subjectname'       => 'subject|name',
1359         'bib.subjectoccupation' => 'keyword',
1360
1361         # Keyword class:
1362         'srw.serverchoice'      => 'keyword',
1363
1364         # Identifiers:
1365         'dc.identifier'         => 'keyword',
1366
1367         # Dates:
1368         'bib.dateissued'        => undef,
1369         'bib.datecreated'       => undef,
1370         'bib.datevalid'         => undef,
1371         'bib.datemodified'      => undef,
1372         'bib.datecopyright'     => undef,
1373
1374         # Resource Type:
1375         'dc.type'               => undef,
1376
1377         # Format:
1378         'dc.format'             => undef,
1379
1380         # Genre:
1381         'bib.genre'             => 'keyword',
1382
1383         # Target Audience:
1384         'bib.audience'          => undef,
1385
1386         # Place of Origin:
1387         'bib.originplace'       => undef,
1388
1389         # Language
1390         'dc.language'           => 'lang',
1391
1392         # Edition
1393         'bib.edition'           => 'keyword',
1394
1395         # Part:
1396         'bib.volume'            => 'keyword',
1397         'bib.issue'             => 'keyword',
1398         'bib.startpage'         => 'keyword',
1399         'bib.endpage'           => 'keyword',
1400
1401         # Issuance:
1402         'bib.issuance'          => 'keyword',
1403     );
1404
1405     sub toEvergreen {
1406         my $self      = shift;
1407         my $qualifier = $self->getQualifier();
1408         my $term      = $self->getTerm();
1409         my $relation  = $self->getRelation();
1410
1411         my $query;
1412         if ( $qualifier ) {
1413
1414             if ( exists($qualifier_map{lc($qualifier)}) ) {
1415                 $qualifier = $qualifier_map{lc($qualifier)} || 'kw';
1416             }
1417
1418
1419             my @modifiers = $relation->getModifiers();
1420
1421             my $base = $relation->getBase();
1422             if ( grep { $base eq $_ } qw/= scr exact all/ ) {
1423
1424                 my $quote_it = 1;
1425                 foreach my $m ( @modifiers ) {
1426                     if( grep { $m->[ 1 ] eq $_ } qw/cql.fuzzy cql.stem cql.relevant cql.word/ ) {
1427                         $quote_it = 0;
1428                         last;
1429                     }
1430                 }
1431
1432                 $quote_it = 0 if ( $base eq 'all' );
1433                 $term = maybeQuote($term) if $quote_it;
1434
1435             } else {
1436                 croak( "Evergreen doesn't support the $base relations" );
1437             }
1438
1439             return "$qualifier:$term";
1440
1441         } else {
1442             return "kw:$term";
1443         }
1444     }
1445 }
1446
1447 1;