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