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