Bug 8202: Add authority export to tools/export.pl
[koha.git] / tools / export.pl
1 #!/usr/bin/perl
2
3 #
4 # This file is part of Koha.
5 #
6 # Koha is free software; you can redistribute it and/or modify it under the
7 # terms of the GNU General Public License as published by the Free Software
8 # Foundation; either version 2 of the License, or (at your option) any later
9 # version.
10 #
11 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
12 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
13 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License along with
16 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
17 # Suite 330, Boston, MA  02111-1307 USA
18
19
20 use strict;
21 use warnings;
22 use C4::Auth;
23 use C4::Output;
24 use C4::Biblio;  # GetMarcBiblio GetXmlBiblio
25 use C4::AuthoritiesMarc; # GetAuthority
26 use CGI;
27 use C4::Koha;    # GetItemTypes
28 use C4::Branch;  # GetBranches
29
30 my $query = new CGI;
31 my $op=$query->param("op") || '';
32 my $filename=$query->param("filename");
33 my $dbh=C4::Context->dbh;
34 my $marcflavour = C4::Context->preference("marcflavour");
35
36 my ($template, $loggedinuser, $cookie)
37     = get_template_and_user
38     (
39         {
40             template_name => "tools/export.tmpl",
41             query => $query,
42             type => "intranet",
43             authnotrequired => 0,
44             flagsrequired => {tools => 'export_catalog'},
45             debug => 1,
46             }
47     );
48
49         my $limit_ind_branch=(C4::Context->preference('IndependantBranches') &&
50               C4::Context->userenv &&
51               !(C4::Context->userenv->{flags} & 1) &&
52               C4::Context->userenv->{branch}?1:0);
53         my $branches = GetBranches($limit_ind_branch);    
54     my $branch                = $query->param("branch") || '';
55         if ( C4::Context->preference("IndependantBranches") &&
56          !(C4::Context->userenv->{flags} & 1) ) {
57         $branch = C4::Context->userenv->{'branch'};
58         }
59
60 if ($op eq "export") {
61     binmode STDOUT, ':encoding(UTF-8)';
62         print $query->header(   -type => 'application/octet-stream', 
63                             -charset => 'utf-8',
64                             -attachment=>$filename);
65      
66     my $record_type        = $query->param("record_type");
67     my $output_format      = $query->param("output_format");
68     my $dont_export_fields = $query->param("dont_export_fields");
69     my @sql_params;
70     my $sql_query;
71
72     my $StartingBiblionumber = $query->param("StartingBiblionumber");
73     my $EndingBiblionumber   = $query->param("EndingBiblionumber");
74     my $itemtype             = $query->param("itemtype");
75     my $start_callnumber     = $query->param("start_callnumber");
76     my $end_callnumber       = $query->param("end_callnumber");
77     my $start_accession =
78       ( $query->param("start_accession") )
79       ? C4::Dates->new( $query->param("start_accession") )
80       : '';
81     my $end_accession =
82       ( $query->param("end_accession") )
83       ? C4::Dates->new( $query->param("end_accession") )
84       : '';
85     my $dont_export_items    = $query->param("dont_export_item");
86     my $strip_nonlocal_items = $query->param("strip_nonlocal_items");
87
88     my $starting_authid = $query->param('starting_authid');
89     my $ending_authid   = $query->param('ending_authid');
90     my $authtype        = $query->param('authtype');
91
92     if ( $record_type eq 'bibs' ) {
93         my $items_filter =
94             $branch || $start_callnumber || $end_callnumber ||
95             $start_accession || $end_accession ||
96             ($itemtype && C4::Context->preference('item-level_itypes'));
97         $sql_query = $items_filter ?
98             "SELECT DISTINCT biblioitems.biblionumber
99             FROM biblioitems JOIN items
100             USING (biblionumber) WHERE 1"
101             :
102             "SELECT biblioitems.biblionumber FROM biblioitems WHERE biblionumber >0 ";
103
104         if ( $StartingBiblionumber ) {
105             $sql_query .= " AND biblioitems.biblionumber >= ? ";
106             push @sql_params, $StartingBiblionumber;
107         }
108
109         if ( $EndingBiblionumber ) {
110             $sql_query .= " AND biblioitems.biblionumber <= ? ";
111             push @sql_params, $EndingBiblionumber;
112         }
113
114         if ($branch) {
115             $sql_query .= " AND homebranch = ? ";
116             push @sql_params, $branch;
117         }
118
119         if ($start_callnumber) {
120             $sql_query .= " AND itemcallnumber <= ? ";
121             push @sql_params, $start_callnumber;
122         }
123
124         if ($end_callnumber) {
125             $sql_query .= " AND itemcallnumber >= ? ";
126             push @sql_params, $end_callnumber;
127         }
128         if ($start_accession) {
129             $sql_query .= " AND dateaccessioned >= ? ";
130             push @sql_params, $start_accession->output('iso');
131         }
132
133         if ($end_accession) {
134             $sql_query .= " AND dateaccessioned <= ? ";
135             push @sql_params, $end_accession->output('iso');
136         }
137
138         if ( $itemtype ) {
139             $sql_query .= (C4::Context->preference('item-level_itypes')) ? " AND items.itype = ? " : " AND biblioitems.itemtype = ?";
140             push @sql_params, $itemtype;
141         }
142     }
143     elsif ( $record_type eq 'auths' ) {
144         $sql_query =
145           "SELECT DISTINCT auth_header.authid FROM auth_header WHERE 1";
146
147         if ($starting_authid) {
148             $sql_query .= " AND auth_header.authid >= ? ";
149             push @sql_params, $starting_authid;
150         }
151
152         if ($ending_authid) {
153             $sql_query .= " AND auth_header.authid <= ? ";
154             push @sql_params, $ending_authid;
155         }
156
157         if ($authtype) {
158             $sql_query .= " AND auth_header.authtypecode = ? ";
159             push @sql_params, $authtype;
160         }
161     }
162
163     my $sth = $dbh->prepare($sql_query);
164     $sth->execute(@sql_params);
165
166     while ( my ($recordid) = $sth->fetchrow ) {
167         my $record;
168         if ( $record_type eq 'bibs' ) {
169             $record = eval { GetMarcBiblio($recordid); };
170
171      # FIXME: decide how to handle records GetMarcBiblio can't parse or retrieve
172             if ($@) {
173                 next;
174             }
175             next if not defined $record;
176             C4::Biblio::EmbedItemsInMarcBiblio( $record, $recordid )
177               unless $dont_export_items;
178             if ( $strip_nonlocal_items || $limit_ind_branch ) {
179                 my ( $homebranchfield, $homebranchsubfield ) =
180                   GetMarcFromKohaField( 'items.homebranch', '' );
181                 for my $itemfield ( $record->field($homebranchfield) ) {
182
183 # if stripping nonlocal items, use loggedinuser's branch if they didn't select one
184                     $branch = C4::Context->userenv->{'branch'} unless $branch;
185                     $record->delete_field($itemfield)
186                       if (
187                         $itemfield->subfield($homebranchsubfield) ne $branch );
188                 }
189             }
190         }
191         elsif ( $record_type eq 'auths' ) {
192             $record = C4::AuthoritiesMarc::GetAuthority($recordid);
193             next if not defined $record;
194         }
195
196         if ( $dont_export_fields ) {
197             my @fields = split " ", $dont_export_fields;
198             foreach ( @fields ) {
199                 /^(\d*)(\w)?$/;
200                 my $field = $1;
201                 my $subfield = $2;
202                 # skip if this record doesn't have this field
203                 next if not defined $record->field($field);
204                 if( $subfield ) {
205                     $record->field($field)->delete_subfields($subfield);
206                 }
207                 else {
208                     $record->delete_field($record->field($field));
209                 }
210             }
211         }
212         if ( $output_format eq "xml" ) {
213             print $record->as_xml_record($marcflavour);
214         }
215         else {
216             print $record->as_usmarc();
217         }
218     }
219     exit;
220
221 }    # if export
222
223 else {
224
225     my $itemtypes = GetItemTypes;
226     my @itemtypesloop;
227     foreach my $thisitemtype (sort keys %$itemtypes) {
228         my %row =
229             (
230                 value => $thisitemtype,
231                 description => $itemtypes->{$thisitemtype}->{'description'},
232             );
233        push @itemtypesloop, \%row;
234     }
235     my @branchloop;
236     for my $thisbranch (
237         sort { $branches->{$a}->{branchname} cmp $branches->{$b}->{branchname} }
238         keys %{$branches}
239       ) {
240         push @branchloop,
241           { value      => $thisbranch,
242             selected   => $thisbranch eq $branch,
243             branchname => $branches->{$thisbranch}->{'branchname'},
244           };
245     }
246
247     my $authtypes = getauthtypes;
248     my @authtypesloop;
249     foreach my $thisauthtype ( sort keys %$authtypes ) {
250         next unless $thisauthtype;
251         my %row = (
252             value       => $thisauthtype,
253             description => $authtypes->{$thisauthtype}->{'authtypetext'},
254         );
255         push @authtypesloop, \%row;
256     }
257
258     $template->param(
259         branchloop               => \@branchloop,
260         itemtypeloop             => \@itemtypesloop,
261         DHTMLcalendar_dateformat => C4::Dates->DHTMLcalendar(),
262         authtypeloop             => \@authtypesloop,
263     );
264
265     output_html_with_http_headers $query, $cookie, $template->output;
266 }