]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/WWW/Exporter.pm
allow the exporter to accept a container id, for exporting buckets etc
[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 $authid = $cgi->cookie('ses') || $cgi->param('ses');
92                 my $auth = verify_login($authid);
93                 if (!$auth) {
94                         return 403;
95                 }
96                 my $recs = $ses->request( 'open-ils.cstore.direct.container.biblio_record_entry_bucket_item.search.atomic', { bucket => $cointainer } )->gather(1);
97                 @records = map { ($_->target_biblio_record_entry) } @$recs;
98         }
99
100         return show_template($r) unless (@records);
101
102         my $type = $cgi->param('rectype') || 'biblio';
103         if ($type ne 'biblio' && $type ne 'authority') {
104                 return 400;
105         }
106
107         my $tcn_v = 'tcn_value';
108         my $tcn_s = 'tcn_source';
109
110         if ($type eq 'authority') {
111                 $tcn_v = 'arn_value';
112                 $tcn_s = 'arn_source';
113         }
114
115         my $holdings = $cgi->param('holdings') if ($type eq 'biblio');
116         my $location = $cgi->param('location') || 'gaaagpl'; # just because...
117
118         my $format = $cgi->param('format') || 'USMARC';
119         $format = uc($format);
120
121         my $encoding = $cgi->param('encoding') || 'UTF-8';
122         $encoding = uc($encoding);
123
124         my $filename = $cgi->param('filename') || "export.$type.$encoding.$format";
125
126         binmode(STDOUT, ':raw') if ($encoding ne 'UTF-8');
127         binmode(STDOUT, ':utf8') if ($encoding eq 'UTF-8');
128
129         if (!grep { uc($format) eq $_ } @formats) {
130                 return 400;
131         }
132
133         if ($format ne 'XML') {
134                 my $ftype = 'MARC::File::' . $format;
135                 $ftype->require;
136         }
137
138
139         $r->headers_out->set("Content-Disposition" => "inline; filename=$filename");
140
141         if (uc($format) eq 'XML') {
142                 $r->content_type('application/xml');
143         } else {
144                 $r->content_type('application/octet-stream');
145         }
146
147         $r->print( <<"  HEADER" ) if (uc($format) eq 'XML');
148 <?xml version="1.0" encoding="$encoding"?>
149 <collection xmlns='http://www.loc.gov/MARC21/slim'>
150         HEADER
151
152         my %orgs;
153         my %shelves;
154
155         my $flesh = {};
156         if ($holdings) {
157
158                 my $req = $ses->request( 'open-ils.cstore.direct.actor.org_unit.search', { id => { '!=' => undef } } );
159
160                 while (my $o = $req->recv) {
161                         next if ($req->failed);
162                         $o = $o->content;
163                         last unless ($o);
164                         $orgs{$o->id} = $o;
165                 }
166                 $req->finish;
167
168                 $req = $ses->request( 'open-ils.cstore.direct.asset.copy_location.search', { id => { '!=' => undef } } );
169
170                 while (my $s = $req->recv) {
171                         next if ($req->failed);
172                         $s = $s->content;
173                         last unless ($s);
174                         $shelves{$s->id} = $s;
175                 }
176                 $req->finish;
177
178                 $flesh = { flesh => 2, flesh_fields => { bre => [ 'call_numbers' ], acn => [ 'copies' ] } };
179         }
180
181         for my $i ( @records ) {
182                 my $bib;
183                 try {
184                         local $SIG{ALRM} = sub { die "TIMEOUT\n" };
185                         alarm(1);
186                         $bib = $ses->request( "open-ils.cstore.direct.$type.record_entry.retrieve", $i, $flesh )->gather(1);
187                         alarm(0);
188                 } otherwise {
189                         warn "\n!!!!!! Timed out trying to read record $i\n";
190                 };
191                 alarm(0);
192
193                 next unless $bib;
194
195                 if (uc($format) eq 'BRE') {
196                         $r->print( OpenSRF::Utils::JSON->perl2JSON($bib) );
197                         next;
198                 }
199
200                 try {
201
202                         my $req = MARC::Record->new_from_xml( $bib->marc, $encoding, $format );
203                         $req->delete_field( $_ ) for ($req->field(901));
204
205                         $req->append_fields(
206                                 MARC::Field->new(
207                                         901, '', '', 
208                                         a => $bib->$tcn_v,
209                                         b => $bib->$tcn_s,
210                                         c => $bib->id
211                                 )
212                         );
213
214
215                         if ($holdings) {
216                                 my $cn_list = $bib->call_numbers;
217                                 if ($cn_list && @$cn_list) {
218
219                                         my $cp_list = [ map { @{ $_->copies } } @$cn_list ];
220                                         if ($cp_list && @$cp_list) {
221
222                                                 my %cn_map;
223                                                 push @{$cn_map{$_->call_number}}, $_ for (@$cp_list);
224                                         
225                                                 for my $cn ( @$cn_list ) {
226                                                         my $cn_map_list = $cn_map{$cn->id};
227         
228                                                         for my $cp ( @$cn_map_list ) {
229                                         
230                                                                 $req->append_fields(
231                                                                         MARC::Field->new(
232                                                                                 852, '4', '', 
233                                                                                 a => $location,
234                                                                                 b => $orgs{$cn->owning_lib}->shortname,
235                                                                                 b => $orgs{$cp->circ_lib}->shortname,
236                                                                                 c => $shelves{$cp->location}->name,
237                                                                                 j => $cn->label,
238                                                                                 ($cp->circ_modifier ? ( g => $cp->circ_modifier ) : ()),
239                                                                                 p => $cp->barcode,
240                                                                                 ($cp->price ? ( y => $cp->price ) : ()),
241                                                                                 ($cp->copy_number ? ( t => $cp->copy_number ) : ()),
242                                                                                 ($cp->ref eq 't' ? ( x => 'reference' ) : ()),
243                                                                                 ($cp->holdable eq 'f' ? ( x => 'unholdable' ) : ()),
244                                                                                 ($cp->circulate eq 'f' ? ( x => 'noncirculating' ) : ()),
245                                                                                 ($cp->opac_visible eq 'f' ? ( x => 'hidden' ) : ()),
246                                                                         )
247                                                                 );
248
249                                                         }
250                                                 }
251                                         }
252                                 }
253                         }
254
255                         if (uc($format) eq 'XML') {
256                                 my $x = $req->as_xml_record;
257                                 $x =~ s/^<\?xml version="1.0" encoding="UTF-8"\?>//o;
258                                 $r->print($x);
259                         } elsif (uc($format) eq 'UNIMARC') {
260                                 $r->print($req->as_unimarc);
261                         } elsif (uc($format) eq 'USMARC') {
262                                 $r->print($req->as_usmarc);
263                         }
264
265             $r->rflush();
266
267                 } otherwise {
268                         my $e = shift;
269                         warn "\n$e\n";
270                 };
271
272         }
273
274         $r->print("</collection>\n") if ($format eq 'XML');
275
276         return Apache2::Const::OK;
277
278 }
279
280 sub verify_login {
281         my $auth_token = shift;
282         return undef unless $auth_token;
283
284         my $user = OpenSRF::AppSession
285                 ->create("open-ils.auth")
286                 ->request( "open-ils.auth.session.retrieve", $auth_token )
287                 ->gather(1);
288
289         if (ref($user) eq 'HASH' && $user->{ilsevent} == 1001) {
290                 return undef;
291         }
292
293         return $user if ref($user);
294         return undef;
295 }
296
297 sub show_template {
298         my $r = shift;
299
300         $r->content_type('text/html');
301         $r->print(<<HTML);
302
303 <html>
304         <head>
305                 <title>Record Export</title>
306         </head>
307         <body>
308                 <form method="POST" enctype="multipart/form-data">
309                         Use field number <input type="text" size="2" maxlength="2" name="idcolumn" value="0"/> (starting from 0)
310                         from CSV file <input type="file" name="idfile"/>
311                         <br/><br/> <b>or</b> <br/><br/>
312                         Record ID <input type="text" size="12" maxlength="12" name="id"/>
313                         <br/><br/> Record Type:
314                         <select name="rectype">
315                                 <option value="biblio">Bibliographic Records</option>
316                                 <option value="authority">Authority Records</option>
317                         </select>
318                         <br/> Record Fromat:
319                         <select name="format">
320                                 <option value="USMARC">MARC21</option>
321                                 <option value="UNIMARC">UNIMARC</option>
322                                 <option value="XML">MARC XML</option>
323                                 <option value="BRE">Evergreen BRE</option>
324                         </select>
325                         <br/> Record Encoding:
326                         <select name="encoding">
327                                 <option value="UTF-8">UTF-8</option>
328                                 <option value="MARC8">MARC8</option>
329                         </select>
330                         <br/> Include holdings in Bibliographic Records:
331                         <input type="checkbox" name="holdings" value="1">
332                         <br/><br/><input type="submit" value="Retrieve Records"/>
333                 </form>
334         </body>
335 </html>
336
337 HTML
338
339         return Apache2::Const::OK;
340 }
341
342 1;