]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/WWW/Exporter.pm
fba5fe6d8592b9f4acdb3e42eb0e97681b642b58
[Evergreen.git] / Open-ILS / src / perlmods / OpenILS / WWW / Exporter.pm
1 package OpenILS::WWW::Exporter;
2 use strict;
3 use warnings;
4 use bytes;
5
6 use Apache2::Log;
7 use Apache2::Const -compile => qw(OK REDIRECT DECLINED NOT_FOUND :log);
8 use APR::Const    -compile => qw(:error SUCCESS);
9 use APR::Table;
10
11 use Apache2::RequestRec ();
12 use Apache2::RequestIO ();
13 use Apache2::RequestUtil;
14 use CGI;
15 use Data::Dumper;
16 use Text::CSV;
17
18 use OpenSRF::EX qw(:try);
19 use OpenSRF::Utils qw/:datetime/;
20 use OpenSRF::Utils::Cache;
21 use OpenSRF::System;
22 use OpenSRF::AppSession;
23 use XML::LibXML;
24 use XML::LibXSLT;
25
26 use Encode;
27 use Unicode::Normalize;
28 use OpenILS::Utils::Fieldmapper;
29 use OpenSRF::Utils::Logger qw/$logger/;
30
31 use MARC::Record;
32 use MARC::File::XML;
33
34 use UNIVERSAL::require;
35
36 our @formats = qw/USMARC UNIMARC XML BRE/;
37
38 # set the bootstrap config and template include directory when
39 # this module is loaded
40 my $bootstrap;
41
42 sub import {
43         my $self = shift;
44         $bootstrap = shift;
45 }
46
47
48 sub child_init {
49         OpenSRF::System->bootstrap_client( config_file => $bootstrap );
50 }
51
52 sub handler {
53         my $r = shift;
54         my $cgi = new CGI;
55
56         # find some IDs ...
57         my @records;
58
59         @records = map { $_ ? ($_) : () } $cgi->param('id');
60
61         if (!@records) { # try for a file
62                 my $file = $cgi->param('idfile');
63                 if ($file) {
64                         my $col = $cgi->param('idcolumn') || 0;
65                         my $csv = new Text::CSV;
66
67                         while (<$file>) {
68                                 chomp;
69                                 $csv->parse($_);
70                                 my @data = $csv->fields;
71                                 my $id = $data[$col];
72                                 $id =~ s/\D+//o;
73                                 next unless ($id);
74                                 push @records, $id;
75                         }
76                 }
77         }
78
79         if (!@records) { # try pathinfo
80                 my $path_rec = $cgi->path_info();
81                 if ($path_rec) {
82                         @records = map { $_ ? ($_) : () } split '/', $path_rec;
83                 }
84         }
85
86         my $ses = OpenSRF::AppSession->create('open-ils.cstore');
87
88         # still no records ...
89         my $container = $cgi->param('containerid');
90         if ($container) {
91                 my $bucket = $ses->request( 'open-ils.cstore.direct.container.biblio_record_entry_bucket.retrieve', $container )->gather(1);
92         if ($bucket->pub !~ /t|1/oi) {
93                 my $authid = $cgi->cookie('ses') || $cgi->param('ses');
94                 my $auth = verify_login($authid);
95                     if (!$auth) {
96                             return 403;
97                 }
98         }
99                 my $recs = $ses->request( 'open-ils.cstore.direct.container.biblio_record_entry_bucket_item.search.atomic', { bucket => $container } )->gather(1);
100                 @records = map { ($_->target_biblio_record_entry) } @$recs;
101         }
102
103         return show_template($r) unless (@records);
104
105         my $type = $cgi->param('rectype') || 'biblio';
106         if ($type ne 'biblio' && $type ne 'authority') {
107                 return 400;
108         }
109
110         my $tcn_v = 'tcn_value';
111         my $tcn_s = 'tcn_source';
112
113         if ($type eq 'authority') {
114                 $tcn_v = 'arn_value';
115                 $tcn_s = 'arn_source';
116         }
117
118         my $holdings = $cgi->param('holdings') if ($type eq 'biblio');
119         my $location = $cgi->param('location') || 'gaaagpl'; # just because...
120
121         my $format = $cgi->param('format') || 'USMARC';
122         $format = uc($format);
123
124         my $encoding = $cgi->param('encoding') || 'UTF-8';
125         $encoding = uc($encoding);
126
127         my $filename = $cgi->param('filename') || "export.$type.$encoding.$format";
128
129         binmode(STDOUT, ':raw') if ($encoding ne 'UTF-8');
130         binmode(STDOUT, ':utf8') if ($encoding eq 'UTF-8');
131
132         if (!grep { uc($format) eq $_ } @formats) {
133                 return 400;
134         }
135
136         if ($format ne 'XML') {
137                 my $ftype = 'MARC::File::' . $format;
138                 $ftype->require;
139         }
140
141
142         $r->headers_out->set("Content-Disposition" => "inline; filename=$filename");
143
144         if (uc($format) eq 'XML') {
145                 $r->content_type('application/xml');
146         } else {
147                 $r->content_type('application/octet-stream');
148         }
149
150         $r->print( <<"  HEADER" ) if (uc($format) eq 'XML');
151 <?xml version="1.0" encoding="$encoding"?>
152 <collection xmlns='http://www.loc.gov/MARC21/slim'>
153         HEADER
154
155         my %orgs;
156         my %shelves;
157         my %statuses;
158
159         my $flesh = {};
160         if ($holdings) {
161
162                 my $req = $ses->request( 'open-ils.cstore.direct.actor.org_unit.search', { id => { '!=' => undef } } );
163
164                 while (my $o = $req->recv) {
165                         next if ($req->failed);
166                         $o = $o->content;
167                         last unless ($o);
168                         $orgs{$o->id} = $o;
169                 }
170                 $req->finish;
171
172                 $req = $ses->request( 'open-ils.cstore.direct.asset.copy_location.search', { id => { '!=' => undef } } );
173
174                 while (my $s = $req->recv) {
175                         next if ($req->failed);
176                         $s = $s->content;
177                         last unless ($s);
178                         $shelves{$s->id} = $s;
179                 }
180                 $req->finish;
181
182                 $req = $ses->request( 'open-ils.cstore.direct.config.copy_status.search', { id => { '!=' => undef } } );
183
184                 while (my $s = $req->recv) {
185                         next if ($req->failed);
186                         $s = $s->content;
187                         last unless ($s);
188                         $statuses{$s->id} = $s;
189                 }
190                 $req->finish;
191
192                 $flesh = { flesh => 2, flesh_fields => { bre => [ 'call_numbers' ], acn => [ 'copies' ] } };
193         }
194
195         for my $i ( @records ) {
196                 my $bib;
197                 try {
198                         local $SIG{ALRM} = sub { die "TIMEOUT\n" };
199                         alarm(1);
200                         $bib = $ses->request( "open-ils.cstore.direct.$type.record_entry.retrieve", $i, $flesh )->gather(1);
201                         alarm(0);
202                 } otherwise {
203                         warn "\n!!!!!! Timed out trying to read record $i\n";
204                 };
205                 alarm(0);
206
207                 next unless $bib;
208
209                 if (uc($format) eq 'BRE') {
210                         $r->print( OpenSRF::Utils::JSON->perl2JSON($bib) );
211                         next;
212                 }
213
214                 try {
215
216                         my $req = MARC::Record->new_from_xml( $bib->marc, $encoding, $format );
217                         $req->delete_field( $_ ) for ($req->field(901));
218
219                         $req->append_fields(
220                                 MARC::Field->new(
221                                         901, '', '', 
222                                         a => $bib->$tcn_v,
223                                         b => $bib->$tcn_s,
224                                         c => $bib->id
225                                 )
226                         );
227
228
229                         if ($holdings) {
230                                 my $cn_list = $bib->call_numbers;
231                                 if ($cn_list && @$cn_list) {
232
233                                         my $cp_list = [ map { @{ $_->copies } } @$cn_list ];
234                                         if ($cp_list && @$cp_list) {
235
236                                                 my %cn_map;
237                                                 push @{$cn_map{$_->call_number}}, $_ for (@$cp_list);
238                                         
239                                                 for my $cn ( @$cn_list ) {
240                                                         my $cn_map_list = $cn_map{$cn->id};
241         
242                                                         for my $cp ( @$cn_map_list ) {
243                                         
244                                                                 $req->append_fields(
245                                                                         MARC::Field->new(
246                                                                                 852, '4', '', 
247                                                                                 a => $location,
248                                                                                 b => $orgs{$cn->owning_lib}->shortname,
249                                                                                 b => $orgs{$cp->circ_lib}->shortname,
250                                                                                 c => $shelves{$cp->location}->name,
251                                                                                 j => $cn->label,
252                                                                                 ($cp->circ_modifier ? ( g => $cp->circ_modifier ) : ()),
253                                                                                 p => $cp->barcode,
254                                                                                 ($cp->price ? ( y => $cp->price ) : ()),
255                                                                                 ($cp->copy_number ? ( t => $cp->copy_number ) : ()),
256                                                                                 ($cp->ref eq 't' ? ( x => 'reference' ) : ()),
257                                                                                 ($cp->holdable eq 'f' ? ( x => 'unholdable' ) : ()),
258                                                                                 ($cp->circulate eq 'f' ? ( x => 'noncirculating' ) : ()),
259                                                                                 ($cp->opac_visible eq 'f' ? ( x => 'hidden' ) : ()),
260                                                                                 z => $statuses{$cp->status}->name,
261                                                                         )
262                                                                 );
263
264                                                         }
265                                                 }
266                                         }
267                                 }
268                         }
269
270                         if (uc($format) eq 'XML') {
271                                 my $x = $req->as_xml_record;
272                                 $x =~ s/^<\?xml version="1.0" encoding="UTF-8"\?>//o;
273                                 $r->print($x);
274                         } elsif (uc($format) eq 'UNIMARC') {
275                                 $r->print($req->as_unimarc);
276                         } elsif (uc($format) eq 'USMARC') {
277                                 $r->print($req->as_usmarc);
278                         }
279
280             $r->rflush();
281
282                 } otherwise {
283                         my $e = shift;
284                         warn "\n$e\n";
285                 };
286
287         }
288
289         $r->print("</collection>\n") if ($format eq 'XML');
290
291         return Apache2::Const::OK;
292
293 }
294
295 sub verify_login {
296         my $auth_token = shift;
297         return undef unless $auth_token;
298
299         my $user = OpenSRF::AppSession
300                 ->create("open-ils.auth")
301                 ->request( "open-ils.auth.session.retrieve", $auth_token )
302                 ->gather(1);
303
304         if (ref($user) eq 'HASH' && $user->{ilsevent} == 1001) {
305                 return undef;
306         }
307
308         return $user if ref($user);
309         return undef;
310 }
311
312 sub show_template {
313         my $r = shift;
314
315         $r->content_type('text/html');
316         $r->print(<<HTML);
317
318 <html>
319         <head>
320                 <title>Record Export</title>
321         </head>
322         <body>
323                 <form method="POST" enctype="multipart/form-data">
324                         Use field number <input type="text" size="2" maxlength="2" name="idcolumn" value="0"/> (starting from 0)
325                         from CSV file <input type="file" name="idfile"/>
326                         <br/><br/> <b>or</b> <br/><br/>
327                         Record ID <input type="text" size="12" maxlength="12" name="id"/>
328                         <br/><br/> Record Type:
329                         <select name="rectype">
330                                 <option value="biblio">Bibliographic Records</option>
331                                 <option value="authority">Authority Records</option>
332                         </select>
333                         <br/> Record Format:
334                         <select name="format">
335                                 <option value="USMARC">MARC21</option>
336                                 <option value="UNIMARC">UNIMARC</option>
337                                 <option value="XML">MARC XML</option>
338                                 <option value="BRE">Evergreen BRE</option>
339                         </select>
340                         <br/> Record Encoding:
341                         <select name="encoding">
342                                 <option value="UTF-8">UTF-8</option>
343                                 <option value="MARC8">MARC8</option>
344                         </select>
345                         <br/> Include holdings in Bibliographic Records:
346                         <input type="checkbox" name="holdings" value="1">
347                         <br/><br/><input type="submit" value="Retrieve Records"/>
348                 </form>
349         </body>
350 </html>
351
352 HTML
353
354         return Apache2::Const::OK;
355 }
356
357 1;