Fix release notes typo
[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 use Modern::Perl;
20 use MARC::File::XML;
21 use List::MoreUtils qw(uniq);
22 use Getopt::Long;
23 use CGI;
24 use C4::Auth;
25 use C4::AuthoritiesMarc;    # GetAuthority
26 use C4::Biblio;             # GetMarcBiblio
27 use C4::Branch;             # GetBranches
28 use C4::Csv;
29 use C4::Koha;               # GetItemTypes
30 use C4::Output;
31 use C4::Record;
32
33 my $query = new CGI;
34
35 my $clean;
36 my $output_format;
37 my $dont_export_items;
38 my $deleted_barcodes;
39 my $timestamp;
40 my $record_type;
41 my $help;
42 my $op       = $query->param("op")       || '';
43 my $filename = $query->param("filename") || 'koha.mrc';
44 my $dbh      = C4::Context->dbh;
45 my $marcflavour = C4::Context->preference("marcflavour");
46 my $format = $query->param("format") || 'iso2709';
47
48 # Checks if the script is called from commandline
49 my $commandline = not defined $ENV{GATEWAY_INTERFACE};
50
51 if ( $commandline ) {
52
53     # Getting parameters
54     $op = 'export';
55     GetOptions(
56         'format=s'          => \$output_format,
57         'date=s'            => \$timestamp,
58         'dont_export_items' => \$dont_export_items,
59         'deleted_barcodes'  => \$deleted_barcodes,
60         'clean'             => \$clean,
61         'filename=s'        => \$filename,
62         'record-type=s'     => \$record_type,
63         'help|?'            => \$help
64     );
65
66     if ($help) {
67         print <<_USAGE_;
68 export.pl [--format=format] [--date=date] [--record-type=TYPE] [--dont_export_items] [--deleted_barcodes] [--clean] --filename=outputfile
69
70
71  --format=FORMAT        FORMAT is either 'xml' or 'marc' (default)
72
73  --date=DATE            DATE should be entered as the 'dateformat' syspref is
74                         set (dd/mm/yyyy for metric, yyyy-mm-dd for iso,
75                         mm/dd/yyyy for us) records exported are the ones that
76                         have been modified since DATE
77
78  --record-type=TYPE     TYPE is 'bibs' or 'auths'
79
80  --deleted_barcodes     If used, a list of barcodes of items deleted since DATE
81                         is produced (or from all deleted items if no date is
82                         specified). Used only if TYPE is 'bibs'
83
84  --clean                removes NSE/NSB
85 _USAGE_
86         exit;
87     }
88
89     # Default parameters values :
90     $output_format     ||= 'marc';
91     $timestamp         ||= '';
92     $dont_export_items ||= 0;
93     $deleted_barcodes  ||= 0;
94     $clean             ||= 0;
95     $record_type       ||= "bibs";
96
97     # Redirect stdout
98     open STDOUT, '>', $filename if $filename;
99
100 }
101 else {
102
103     $op       = $query->param("op")       || '';
104     $filename = $query->param("filename") || 'koha.mrc';
105     $filename =~ s/(\r|\n)//;
106
107 }
108
109 my ( $template, $loggedinuser, $cookie, $flags ) = get_template_and_user(
110     {
111         template_name   => "tools/export.tmpl",
112         query           => $query,
113         type            => "intranet",
114         authnotrequired => $commandline,
115         flagsrequired   => { tools => 'export_catalog' },
116         debug           => 1,
117     }
118 );
119
120 my $limit_ind_branch =
121   (      C4::Context->preference('IndependentBranches')
122       && C4::Context->userenv
123       && !C4::Context->IsSuperLibrarian()
124       && C4::Context->userenv->{branch} ) ? 1 : 0;
125
126 my $branch = $query->param("branch") || '';
127 if (   C4::Context->preference("IndependentBranches")
128     && C4::Context->userenv
129     && !C4::Context->IsSuperLibrarian() )
130 {
131     $branch = C4::Context->userenv->{'branch'};
132 }
133
134 my $backupdir = C4::Context->config('backupdir');
135
136 if ( $op eq "export" ) {
137     if ( $format eq "iso2709" or $format eq "xml" ) {
138         my $charset  = 'utf-8';
139         my $mimetype = 'application/octet-stream';
140         binmode STDOUT, ':encoding(UTF-8)';
141         if ( $filename =~ m/\.gz$/ ) {
142             $mimetype = 'application/x-gzip';
143             $charset  = '';
144             binmode STDOUT;
145         }
146         elsif ( $filename =~ m/\.bz2$/ ) {
147             $mimetype = 'application/x-bzip2';
148             binmode STDOUT;
149             $charset = '';
150         }
151         print $query->header(
152             -type       => $mimetype,
153             -charset    => $charset,
154             -attachment => $filename
155         ) unless ($commandline);
156
157         $record_type = $query->param("record_type") unless ($commandline);
158         $output_format = $query->param("output_format") || 'marc'
159           unless ($commandline);
160         my $export_remove_fields = $query->param("export_remove_fields");
161         my @biblionumbers      = $query->param("biblionumbers");
162         my @itemnumbers        = $query->param("itemnumbers");
163         my @sql_params;
164         my $sql_query;
165         my @recordids;
166
167         my $StartingBiblionumber = $query->param("StartingBiblionumber");
168         my $EndingBiblionumber   = $query->param("EndingBiblionumber");
169         my $itemtype             = $query->param("itemtype");
170         my $start_callnumber     = $query->param("start_callnumber");
171         my $end_callnumber       = $query->param("end_callnumber");
172         $timestamp = ($timestamp) ? C4::Dates->new($timestamp) : ''
173           if ($commandline);
174         my $start_accession =
175           ( $query->param("start_accession") )
176           ? C4::Dates->new( $query->param("start_accession") )
177           : '';
178         my $end_accession =
179           ( $query->param("end_accession") )
180           ? C4::Dates->new( $query->param("end_accession") )
181           : '';
182         $dont_export_items = $query->param("dont_export_item")
183           unless ($commandline);
184
185         my $strip_nonlocal_items = $query->param("strip_nonlocal_items");
186
187         my $biblioitemstable =
188           ( $commandline and $deleted_barcodes )
189           ? 'deletedbiblioitems'
190           : 'biblioitems';
191         my $itemstable =
192           ( $commandline and $deleted_barcodes )
193           ? 'deleteditems'
194           : 'items';
195
196         my $starting_authid = $query->param('starting_authid');
197         my $ending_authid   = $query->param('ending_authid');
198         my $authtype        = $query->param('authtype');
199
200         if ( $record_type eq 'bibs' and not @biblionumbers ) {
201             if ($timestamp) {
202
203             # Specific query when timestamp is used
204             # Actually it's used only with CLI and so all previous filters
205             # are not used.
206             # If one day timestamp is used via the web interface, this part will
207             # certainly have to be rewrited
208                 my ( $query, $params ) = construct_query(
209                     {
210                         recordtype       => $record_type,
211                         timestamp        => $timestamp,
212                         biblioitemstable => $biblioitemstable,
213                     }
214                 );
215                 $sql_query  = $query;
216                 @sql_params = @$params;
217
218             }
219             else {
220                 my ( $query, $params ) = construct_query(
221                     {
222                         recordtype           => $record_type,
223                         biblioitemstable     => $biblioitemstable,
224                         itemstable           => $itemstable,
225                         StartingBiblionumber => $StartingBiblionumber,
226                         EndingBiblionumber   => $EndingBiblionumber,
227                         branch               => $branch,
228                         start_callnumber     => $start_callnumber,
229                         end_callnumber       => $end_callnumber,
230                         start_accession      => $start_accession,
231                         end_accession        => $end_accession,
232                         itemtype             => $itemtype,
233                     }
234                 );
235                 $sql_query  = $query;
236                 @sql_params = @$params;
237             }
238         }
239         elsif ( $record_type eq 'auths' ) {
240             my ( $query, $params ) = construct_query(
241                 {
242                     recordtype      => $record_type,
243                     starting_authid => $starting_authid,
244                     ending_authid   => $ending_authid,
245                     authtype        => $authtype,
246                 }
247             );
248             $sql_query  = $query;
249             @sql_params = @$params;
250
251         }
252         elsif ( $record_type eq 'db' ) {
253             my $successful_export;
254             if ( $flags->{superlibrarian}
255                 && C4::Context->config('backup_db_via_tools') )
256             {
257                 $successful_export = download_backup(
258                     {
259                         directory => "$backupdir",
260                         extension => 'sql',
261                         filename  => "$filename"
262                     }
263                 );
264             }
265             unless ($successful_export) {
266                 my $remotehost = $query->remote_host();
267                 $remotehost =~ s/(\n|\r)//;
268                 warn
269 "A suspicious attempt was made to download the db at '$filename' by someone at "
270                   . $remotehost . "\n";
271             }
272             exit;
273         }
274         elsif ( $record_type eq 'conf' ) {
275             my $successful_export;
276             if ( $flags->{superlibrarian}
277                 && C4::Context->config('backup_conf_via_tools') )
278             {
279                 $successful_export = download_backup(
280                     {
281                         directory => "$backupdir",
282                         extension => 'tar',
283                         filename  => "$filename"
284                     }
285                 );
286             }
287             unless ($successful_export) {
288                 my $remotehost = $query->remote_host();
289                 $remotehost =~ s/(\n|\r)//;
290                 warn
291 "A suspicious attempt was made to download the configuration at '$filename' by someone at "
292                   . $remotehost . "\n";
293             }
294             exit;
295         }
296         elsif (@biblionumbers) {
297             push @recordids, (@biblionumbers);
298         }
299         else {
300
301             # Someone is trying to mess us up
302             exit;
303         }
304
305         unless (@biblionumbers) {
306             my $sth = $dbh->prepare($sql_query);
307             $sth->execute(@sql_params);
308             push @recordids, map {
309                 map { $$_[0] } $_
310             } @{ $sth->fetchall_arrayref };
311         }
312
313         my $xml_header_written = 0;
314         for my $recordid ( uniq @recordids ) {
315             if ($deleted_barcodes) {
316                 my $q = "
317                     SELECT DISTINCT barcode
318                     FROM deleteditems
319                     WHERE deleteditems.biblionumber = ?
320                 ";
321                 my $sth = $dbh->prepare($q);
322                 $sth->execute($recordid);
323                 while ( my $row = $sth->fetchrow_array ) {
324                     print "$row\n";
325                 }
326             }
327             else {
328                 my $record;
329                 if ( $record_type eq 'bibs' ) {
330                     $record = eval { GetMarcBiblio($recordid); };
331
332                     next if $@;
333                     next if not defined $record;
334                     C4::Biblio::EmbedItemsInMarcBiblio( $record, $recordid,
335                         \@itemnumbers )
336                       unless $dont_export_items;
337                     if (   $strip_nonlocal_items
338                         || $limit_ind_branch
339                         || $dont_export_items )
340                     {
341                         my ( $homebranchfield, $homebranchsubfield ) =
342                           GetMarcFromKohaField( 'items.homebranch', '' );
343                         for my $itemfield ( $record->field($homebranchfield) ) {
344
345 # if stripping nonlocal items, use loggedinuser's branch if they didn't select one
346                             $branch = C4::Context->userenv->{'branch'}
347                               unless $branch;
348                             $record->delete_field($itemfield)
349                               if ( $dont_export_items
350                                 || $itemfield->subfield($homebranchsubfield) ne
351                                 $branch );
352                         }
353                     }
354                 }
355                 elsif ( $record_type eq 'auths' ) {
356                     $record = C4::AuthoritiesMarc::GetAuthority($recordid);
357                     next if not defined $record;
358                 }
359
360                 if ($export_remove_fields) {
361                     for my $f ( split / /, $export_remove_fields ) {
362                         if ( $f =~ m/^(\d{3})(.)?$/ ) {
363                             my ( $field, $subfield ) = ( $1, $2 );
364
365                             # skip if this record doesn't have this field
366                             if ( defined $record->field($field) ) {
367                                 if ( defined $subfield ) {
368                                     my @tags = $record->field($field);
369                                     foreach my $t (@tags) {
370                                         $t->delete_subfields($subfield);
371                                     }
372                                 }
373                                 else {
374                                     $record->delete_fields($record->field($field));
375                                 }
376                             }
377                         }
378                     }
379                 }
380                 RemoveAllNsb($record) if ($clean);
381                 if ( $output_format eq "xml" ) {
382                     unless ($xml_header_written) {
383                         MARC::File::XML->default_record_format(
384                             (
385                                      $marcflavour eq 'UNIMARC'
386                                   && $record_type eq 'auths'
387                             ) ? 'UNIMARCAUTH' : $marcflavour
388                         );
389                         print MARC::File::XML::header();
390                         print "\n";
391                         $xml_header_written = 1;
392                     }
393                     print MARC::File::XML::record($record);
394                     print "\n";
395                 }
396                 else {
397                     my (@result_build_tag) = MARC::File::USMARC::_build_tag_directory($record);
398                     if ($result_build_tag[2] > 99999) {
399                         warn "record (number $recordid) length ".$result_build_tag[2]." is larger than the MARC spec allows (99999 bytes)";
400                         next;
401                     }
402                     print $record->as_usmarc();
403                 }
404             }
405         }
406         if ($xml_header_written) {
407             print MARC::File::XML::footer();
408             print "\n";
409         }
410
411         exit;
412     }
413     elsif ( $format eq "csv" ) {
414         my @biblionumbers = uniq $query->param("biblionumbers");
415         my @itemnumbers   = $query->param("itemnumbers");
416         my $output =
417           marc2csv( \@biblionumbers,
418             GetCsvProfileId( C4::Context->preference('ExportWithCsvProfile') ),
419             \@itemnumbers, );
420         print $query->header(
421             -type                        => 'application/octet-stream',
422             -'Content-Transfer-Encoding' => 'binary',
423             -attachment                  => "export.csv"
424         );
425         print $output;
426         exit;
427     }
428 }    # if export
429
430 else {
431
432     my $itemtypes = GetItemTypes;
433     my @itemtypesloop;
434     foreach my $thisitemtype ( sort keys %$itemtypes ) {
435         my %row = (
436             value       => $thisitemtype,
437             description => $itemtypes->{$thisitemtype}->{'description'},
438         );
439         push @itemtypesloop, \%row;
440     }
441     my $branches = GetBranches($limit_ind_branch);
442     my @branchloop;
443     for my $thisbranch (
444         sort { $branches->{$a}->{branchname} cmp $branches->{$b}->{branchname} }
445         keys %{$branches}
446       )
447     {
448         push @branchloop,
449           {
450             value      => $thisbranch,
451             selected   => $thisbranch eq $branch,
452             branchname => $branches->{$thisbranch}->{'branchname'},
453           };
454     }
455
456     my $authtypes = getauthtypes;
457     my @authtypesloop;
458     foreach my $thisauthtype ( sort keys %$authtypes ) {
459         next unless $thisauthtype;
460         my %row = (
461             value       => $thisauthtype,
462             description => $authtypes->{$thisauthtype}->{'authtypetext'},
463         );
464         push @authtypesloop, \%row;
465     }
466
467     if (   $flags->{superlibrarian}
468         && C4::Context->config('backup_db_via_tools')
469         && $backupdir
470         && -d $backupdir )
471     {
472         $template->{VARS}->{'allow_db_export'} = 1;
473         $template->{VARS}->{'dbfiles'}         = getbackupfilelist(
474             { directory => "$backupdir", extension => 'sql' } );
475     }
476
477     if (   $flags->{superlibrarian}
478         && C4::Context->config('backup_conf_via_tools')
479         && $backupdir
480         && -d $backupdir )
481     {
482         $template->{VARS}->{'allow_conf_export'} = 1;
483         $template->{VARS}->{'conffiles'}         = getbackupfilelist(
484             { directory => "$backupdir", extension => 'tar' } );
485     }
486
487     $template->param(
488         branchloop               => \@branchloop,
489         itemtypeloop             => \@itemtypesloop,
490         authtypeloop             => \@authtypesloop,
491         export_remove_fields     => C4::Context->preference("ExportRemoveFields"),
492     );
493
494     output_html_with_http_headers $query, $cookie, $template->output;
495 }
496
497 sub construct_query {
498     my ($params) = @_;
499
500     my ( $sql_query, @sql_params );
501
502     if ( $params->{recordtype} eq "bibs" ) {
503         if ( $params->{timestamp} ) {
504             my $biblioitemstable = $params->{biblioitemstable};
505             $sql_query = " (
506                 SELECT biblionumber
507                 FROM $biblioitemstable
508                   LEFT JOIN items USING(biblionumber)
509                 WHERE $biblioitemstable.timestamp >= ?
510                   OR items.timestamp >= ?
511             ) UNION (
512                 SELECT biblionumber
513                 FROM $biblioitemstable
514                   LEFT JOIN deleteditems USING(biblionumber)
515                 WHERE $biblioitemstable.timestamp >= ?
516                   OR deleteditems.timestamp >= ?
517             ) ";
518             my $ts = $timestamp->output('iso');
519             @sql_params = ( $ts, $ts, $ts, $ts );
520         }
521         else {
522             my $biblioitemstable     = $params->{biblioitemstable};
523             my $itemstable           = $params->{itemstable};
524             my $StartingBiblionumber = $params->{StartingBiblionumber};
525             my $EndingBiblionumber   = $params->{EndingBiblionumber};
526             my $branch               = $params->{branch};
527             my $start_callnumber     = $params->{start_callnumber};
528             my $end_callnumber       = $params->{end_callnumber};
529             my $start_accession      = $params->{start_accession};
530             my $end_accession        = $params->{end_accession};
531             my $itemtype             = $params->{itemtype};
532             my $items_filter =
533                  $branch
534               || $start_callnumber
535               || $end_callnumber
536               || $start_accession
537               || $end_accession
538               || ( $itemtype && C4::Context->preference('item-level_itypes') );
539             $sql_query = $items_filter
540               ? "SELECT DISTINCT $biblioitemstable.biblionumber
541                 FROM $biblioitemstable JOIN $itemstable
542                 USING (biblionumber) WHERE 1"
543               : "SELECT $biblioitemstable.biblionumber FROM $biblioitemstable WHERE biblionumber >0 ";
544
545             if ($StartingBiblionumber) {
546                 $sql_query .= " AND $biblioitemstable.biblionumber >= ? ";
547                 push @sql_params, $StartingBiblionumber;
548             }
549
550             if ($EndingBiblionumber) {
551                 $sql_query .= " AND $biblioitemstable.biblionumber <= ? ";
552                 push @sql_params, $EndingBiblionumber;
553             }
554
555             if ($branch) {
556                 $sql_query .= " AND homebranch = ? ";
557                 push @sql_params, $branch;
558             }
559
560             if ($start_callnumber) {
561                 $sql_query .= " AND itemcallnumber >= ? ";
562                 push @sql_params, $start_callnumber;
563             }
564
565             if ($end_callnumber) {
566                 $sql_query .= " AND itemcallnumber <= ? ";
567                 push @sql_params, $end_callnumber;
568             }
569             if ($start_accession) {
570                 $sql_query .= " AND dateaccessioned >= ? ";
571                 push @sql_params, $start_accession->output('iso');
572             }
573
574             if ($end_accession) {
575                 $sql_query .= " AND dateaccessioned <= ? ";
576                 push @sql_params, $end_accession->output('iso');
577             }
578
579             if ($itemtype) {
580                 $sql_query .=
581                   ( C4::Context->preference('item-level_itypes') )
582                   ? " AND items.itype = ? "
583                   : " AND biblioitems.itemtype = ?";
584                 push @sql_params, $itemtype;
585             }
586         }
587     }
588     elsif ( $params->{recordtype} eq "auths" ) {
589         if ( $params->{timestamp} ) {
590
591             #TODO
592         }
593         else {
594             my $starting_authid = $params->{starting_authid};
595             my $ending_authid   = $params->{ending_authid};
596             my $authtype        = $params->{authtype};
597             $sql_query =
598               "SELECT DISTINCT auth_header.authid FROM auth_header WHERE 1";
599
600             if ($starting_authid) {
601                 $sql_query .= " AND auth_header.authid >= ? ";
602                 push @sql_params, $starting_authid;
603             }
604
605             if ($ending_authid) {
606                 $sql_query .= " AND auth_header.authid <= ? ";
607                 push @sql_params, $ending_authid;
608             }
609
610             if ($authtype) {
611                 $sql_query .= " AND auth_header.authtypecode = ? ";
612                 push @sql_params, $authtype;
613             }
614         }
615     }
616     return ( $sql_query, \@sql_params );
617 }
618
619 sub getbackupfilelist {
620     my $args      = shift;
621     my $directory = $args->{directory};
622     my $extension = $args->{extension};
623     my @files;
624
625     if ( opendir( my $dir, $directory ) ) {
626         while ( my $file = readdir($dir) ) {
627             next unless ( $file =~ m/\.$extension(\.(gz|bz2|xz))?/ );
628             push @files, $file
629               if ( -f "$directory/$file" && -r "$directory/$file" );
630         }
631         closedir($dir);
632     }
633     return \@files;
634 }
635
636 sub download_backup {
637     my $args      = shift;
638     my $directory = $args->{directory};
639     my $extension = $args->{extension};
640     my $filename  = $args->{filename};
641
642     return unless ( $directory && -d $directory );
643     return unless ( $filename =~ m/\.$extension(\.(gz|bz2|xz))?$/ );
644     return if ( $filename =~ m#/# );
645     $filename = "$directory/$filename";
646     return unless ( -f $filename && -r $filename );
647     return unless ( open( my $dump, '<', $filename ) );
648     binmode $dump;
649
650     while ( read( $dump, my $data, 64 * 1024 ) ) {
651         print $data;
652     }
653     close($dump);
654     return 1;
655 }