removing some dead code
[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         $feed->title("Search results for [$class => $terms] at ".$org_unit->[0]->name);
1045
1046         $feed->creator($host);
1047         $feed->update_ts(gmtime_ISO8601());
1048
1049         $feed->_create_node(
1050                 $feed->{item_xpath},
1051                 'http://a9.com/-/spec/opensearch/1.1/',
1052                 'totalResults',
1053                 $recs->{count},
1054         );
1055
1056         $feed->_create_node(
1057                 $feed->{item_xpath},
1058                 'http://a9.com/-/spec/opensearch/1.1/',
1059                 'startIndex',
1060                 $offset + 1,
1061         );
1062
1063         $feed->_create_node(
1064                 $feed->{item_xpath},
1065                 'http://a9.com/-/spec/opensearch/1.1/',
1066                 'itemsPerPage',
1067                 $limit,
1068         );
1069
1070         $feed->link(
1071                 next =>
1072                 $base . "/$version/$org/$type/$class?searchTerms=$terms&searchSort=$sort&searchSortDir=$sortdir&searchLang=$lang&startIndex=" . int($offset + $limit + 1) . "&count=" . $limit =>
1073                 'application/opensearch+xml'
1074         ) if ($offset + $limit < $recs->{count});
1075
1076         $feed->link(
1077                 previous =>
1078                 $base . "/$version/$org/$type/$class?searchTerms=$terms&searchSort=$sort&searchSortDir=$sortdir&searchLang=$lang&startIndex=" . int(($offset - $limit) + 1) . "&count=" . $limit =>
1079                 'application/opensearch+xml'
1080         ) if ($offset);
1081
1082         $feed->link(
1083                 self =>
1084                 $base .  "/$version/$org/$type/$class?searchTerms=$terms&searchSort=$sort&searchSortDir=$sortdir&searchLang=$lang" =>
1085                 'application/opensearch+xml'
1086         );
1087
1088         $feed->link(
1089                 rss =>
1090                 $base .  "/$version/$org/rss2-full/$class?searchTerms=$terms&searchSort=$sort&searchSortDir=$sortdir&searchLang=$lang" =>
1091                 'application/rss+xml'
1092         );
1093
1094         $feed->link(
1095                 alternate =>
1096                 $base .  "/$version/$org/atom-full/$class?searchTerms=$terms&searchSort=$sort&searchSortDir=$sortdir&searchLang=$lang" =>
1097                 'application/atom+xml'
1098         );
1099
1100         $feed->link(
1101                 'html' =>
1102                 $base .  "/$version/$org/html/$class?searchTerms=$terms&searchSort=$sort&searchSortDir=$sortdir&searchLang=$lang" =>
1103                 'text/html'
1104         );
1105
1106         $feed->link(
1107                 'html-full' =>
1108                 $base .  "/$version/$org/html-full/$class?searchTerms=$terms&searchSort=$sort&searchSortDir=$sortdir&searchLang=$lang" =>
1109                 'text/html'
1110         );
1111
1112         $feed->link( 'unapi-server' => $unapi);
1113
1114 #       $feed->link(
1115 #               opac =>
1116 #               $root . "../$lang/skin/default/xml/rresult.xml?rt=list&" .
1117 #                       join('&', map { 'rl=' . $_->[0] } grep { ref $_ && defined $_->[0] } @{$recs->{ids}} ),
1118 #               'text/html'
1119 #       );
1120
1121         print entityize($feed->toString) . "\n";
1122
1123         return Apache2::Const::OK;
1124 }
1125
1126 sub create_record_feed {
1127         my $search = shift;
1128         my $type = shift;
1129         my $records = shift;
1130         my $unapi = shift;
1131
1132         my $lib = uc(shift()) || '-';
1133         my $flesh = shift;
1134         $flesh = 1 if (!defined($flesh));
1135
1136         my $cgi = new CGI;
1137         my $base = $cgi->url;
1138         my $host = $cgi->virtual_host || $cgi->server_name;
1139
1140         my $year = (gmtime())[5] + 1900;
1141
1142         my $flesh_feed = ($type =~ s/-full$//o) ? 1 : 0;
1143
1144         my $feed = new OpenILS::WWW::SuperCat::Feed ($type);
1145         $feed->base($base) if ($flesh);
1146         $feed->unapi($unapi) if ($flesh);
1147
1148         $type = 'atom' if ($type eq 'html');
1149         $type = 'marcxml' if ($type eq 'htmlholdings');
1150
1151         #$records = $supercat->request( "open-ils.supercat.record.object.retrieve", $records )->gather(1);
1152
1153         my $count = 0;
1154         for my $record (@$records) {
1155                 next unless($record);
1156
1157                 #my $rec = $record->id;
1158                 my $rec = $record;
1159
1160                 my $item_tag = "tag:$host,$year:biblio-record_entry/$rec/$lib";
1161                 $item_tag = "tag:$host,$year:isbn/$rec/$lib" if ($search eq 'isbn');
1162
1163                 my $xml = $supercat->request(
1164                         "open-ils.supercat.$search.$type.retrieve",
1165                         $rec
1166                 )->gather(1);
1167                 next unless $xml;
1168
1169                 my $node = $feed->add_item($xml);
1170                 next unless $node;
1171
1172                 $xml = '';
1173                 if ($lib && $type eq 'marcxml' &&  $flesh) {
1174                         my $r = $supercat->request( "open-ils.supercat.$search.holdings_xml.retrieve", $rec, $lib );
1175                         while ( !$r->complete ) {
1176                                 $xml .= join('', map {$_->content} $r->recv);
1177                         }
1178                         $xml .= join('', map {$_->content} $r->recv);
1179                         $node->add_holdings($xml);
1180                 }
1181
1182                 $node->id($item_tag) if ($flesh);
1183                 #$node->update_ts(clense_ISO8601($record->edit_date));
1184                 $node->link(alternate => $feed->unapi . "?id=$item_tag&format=htmlholdings-full" => 'text/html') if ($flesh);
1185                 $node->link(opac => $feed->unapi . "?id=$item_tag&format=opac") if ($flesh);
1186                 $node->link(unapi => $feed->unapi . "?id=$item_tag") if ($flesh);
1187                 $node->link('unapi-id' => $item_tag) if ($flesh);
1188         }
1189
1190         return $feed;
1191 }
1192
1193 sub entityize {
1194         my $stuff = NFC(shift());
1195         $stuff =~ s/&(?!\S+;)/&amp;/gso;
1196         $stuff =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
1197         return $stuff;
1198 }
1199
1200 sub string_browse {
1201         my $apache = shift;
1202         return Apache2::Const::DECLINED if (-e $apache->filename);
1203
1204         my $cgi = new CGI;
1205         my $year = (gmtime())[5] + 1900;
1206
1207         my $host = $cgi->virtual_host || $cgi->server_name;
1208
1209         my $add_path = 0;
1210         if ( $cgi->server_software !~ m|^Apache/2.2| ) {
1211                 my $rel_name = $cgi->url(-relative=>1);
1212                 $add_path = 1 if ($cgi->url(-path_info=>1) !~ /$rel_name$/);
1213         }
1214
1215         my $url = $cgi->url(-path_info=>$add_path);
1216         my $root = (split 'browse', $url)[0];
1217         my $base = (split 'browse', $url)[0] . 'browse';
1218         my $unapi = (split 'browse', $url)[0] . 'unapi';
1219
1220         my $path = $cgi->path_info;
1221         $path =~ s/^\///og;
1222
1223         my ($format,$axis,$site,$string,$page,$page_size) = split '/', $path;
1224         #warn " >>> $format -> $axis -> $site -> $string -> $page -> $page_size ";
1225
1226         $site ||= $cgi->param('searchOrg');
1227         $page ||= $cgi->param('startPage') || 0;
1228         $page_size ||= $cgi->param('count') || 9;
1229
1230         $page = 0 if ($page !~ /^-?\d+$/);
1231
1232         my $prev = join('/', $base,$format,$axis,$site,$string,$page - 1,$page_size);
1233         my $next = join('/', $base,$format,$axis,$site,$string,$page + 1,$page_size);
1234
1235         unless ($string and $axis and grep { $axis eq $_ } keys %browse_types) {
1236                 warn "something's wrong...";
1237                 warn " >>> $format -> $axis -> $site -> $string -> $page -> $page_size ";
1238                 return undef;
1239         }
1240
1241         $string = decode_utf8($string);
1242         $string =~ s/\+/ /go;
1243         $string =~ s/'//go;
1244
1245         my $tree = $supercat->request(
1246                 "open-ils.supercat.$axis.browse",
1247                 $string,
1248                 $site,
1249                 $page_size,
1250                 $page
1251         )->gather(1);
1252
1253         my ($header,$content) = $browse_types{$axis}{$format}->($tree,$prev,$next);
1254         print $header.$content;
1255         return Apache2::Const::OK;
1256 }
1257
1258 sub sru_search {
1259     my $cgi = new CGI;
1260
1261     my $req = SRU::Request->newFromCGI( $cgi );
1262     my $resp = SRU::Response->newFromRequest( $req );
1263
1264     if ( $resp->type eq 'searchRetrieve' ) {
1265                 my $cql_query = $req->query;
1266                 my $search_string = $req->cql->toEvergreen;
1267
1268         my $offset = $req->startRecord;
1269         $offset-- if ($offset);
1270         $offset ||= 0;
1271
1272         my $limit = $req->maximumRecords;
1273         $limit ||= 10;
1274
1275         warn "SRU search string [$cql_query] converted to [$search_string]\n";
1276
1277                 my $recs = $search->request(
1278                         'open-ils.search.biblio.multiclass.query' => {offset => $offset, limit => $limit} => $search_string
1279                 )->gather(1);
1280
1281         my $bre = $supercat->request( 'open-ils.supercat.record.object.retrieve' => [ map { $_->[0] } @{$recs->{ids}} ] )->gather(1);
1282
1283         $resp->addRecord(
1284             SRU::Response::Record->new(
1285                 recordSchema    => 'info:srw/schema/1/marcxml-v1.1',
1286                 recordData => $_->marc
1287             )
1288         ) for @$bre;
1289
1290         $resp->numberOfRecords($recs->{count});
1291
1292         print $cgi->header( -type => 'application/xml' );
1293         print entityize($resp->asXML) . "\n";
1294             return Apache2::Const::OK;
1295     }
1296 }
1297
1298 {
1299     package CQL::BooleanNode;
1300
1301     sub toEvergreen {
1302         my $self     = shift;
1303         my $left     = $self->left();
1304         my $right    = $self->right();
1305         my $leftStr  = $left->toEvergreen;
1306         my $rightStr = $right->toEvergreen();
1307
1308         my $op =  '||' if uc $self->op() eq 'OR';
1309         $op ||=  '&&';
1310
1311         return  "$leftStr $rightStr";
1312     }
1313
1314     package CQL::TermNode;
1315
1316     our %qualifier_map = (
1317
1318         # Som EG qualifiers
1319         'eg.site'               => 'site',
1320         'eg.sort'               => 'sort',
1321         'eg.direction'          => 'dir',
1322         'eg.available'          => 'available',
1323
1324         # Title class:
1325         'dc.title'              => 'title',
1326         'bib.titleabbreviated'  => 'title|abbreviated',
1327         'bib.titleuniform'      => 'title|uniform',
1328         'bib.titletranslated'   => 'title|translated',
1329         'bib.titlealternative'  => 'title',
1330         'bib.titleseries'       => 'series',
1331
1332         # Author/Name class:
1333         'creator'               => 'author',
1334         'dc.creator'            => 'author',
1335         'dc.contributer'        => 'author',
1336         'dc.publisher'          => 'keyword',
1337         'bib.name'              => 'author',
1338         'bib.namepersonal'      => 'author|personal',
1339         'bib.namepersonalfamily'=> 'author|personal',
1340         'bib.namepersonalgiven' => 'author|personal',
1341         'bib.namecorporate'     => 'author|corporate',
1342         'bib.nameconference'    => 'author|converence',
1343
1344         # Subject class:
1345         'dc.subject'            => 'subject',
1346         'bib.subjectplace'      => 'subject|geographic',
1347         'bib.subjecttitle'      => 'keyword',
1348         'bib.subjectname'       => 'subject|name',
1349         'bib.subjectoccupation' => 'keyword',
1350
1351         # Keyword class:
1352         'srw.serverchoice'      => 'keyword',
1353
1354         # Identifiers:
1355         'dc.identifier'         => 'keyword',
1356
1357         # Dates:
1358         'bib.dateissued'        => undef,
1359         'bib.datecreated'       => undef,
1360         'bib.datevalid'         => undef,
1361         'bib.datemodified'      => undef,
1362         'bib.datecopyright'     => undef,
1363
1364         # Resource Type:
1365         'dc.type'               => undef,
1366
1367         # Format:
1368         'dc.format'             => undef,
1369
1370         # Genre:
1371         'bib.genre'             => 'keyword',
1372
1373         # Target Audience:
1374         'bib.audience'          => undef,
1375
1376         # Place of Origin:
1377         'bib.originplace'       => undef,
1378
1379         # Language
1380         'dc.language'           => 'lang',
1381
1382         # Edition
1383         'bib.edition'           => 'keyword',
1384
1385         # Part:
1386         'bib.volume'            => 'keyword',
1387         'bib.issue'             => 'keyword',
1388         'bib.startpage'         => 'keyword',
1389         'bib.endpage'           => 'keyword',
1390
1391         # Issuance:
1392         'bib.issuance'          => 'keyword',
1393     );
1394
1395     sub toEvergreen {
1396         my $self      = shift;
1397         my $qualifier = $self->getQualifier();
1398         my $term      = $self->getTerm();
1399         my $relation  = $self->getRelation();
1400
1401         my $query;
1402         if ( $qualifier ) {
1403
1404             if ( exists($qualifier_map{lc($qualifier)}) ) {
1405                 $qualifier = $qualifier_map{lc($qualifier)} || 'kw';
1406             }
1407
1408
1409             my @modifiers = $relation->getModifiers();
1410
1411             my $base = $relation->getBase();
1412             if ( grep { $base eq $_ } qw/= scr exact all/ ) {
1413
1414                 my $quote_it = 1;
1415                 foreach my $m ( @modifiers ) {
1416                     if( grep { $m->[ 1 ] eq $_ } qw/cql.fuzzy cql.stem cql.relevant cql.word/ ) {
1417                         $quote_it = 0;
1418                         last;
1419                     }
1420                 }
1421
1422                 $quote_it = 0 if ( $base eq 'all' );
1423                 $term = maybeQuote($term) if $quote_it;
1424
1425             } else {
1426                 croak( "Evergreen doesn't support the $base relations" );
1427             }
1428
1429             return "$qualifier:$term";
1430
1431         } else {
1432             return "kw:$term";
1433         }
1434     }
1435 }
1436
1437 1;