Bug 7298: (follow-up) fix translation for CSV strings
[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->userenv->{flags} & 1 )
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->userenv->{flags} & 1 ) )
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                     my @fields = split " ", $export_remove_fields;
362                     foreach (@fields) {
363                         /^(\d*)(\w)?$/;
364                         my $field    = $1;
365                         my $subfield = $2;
366
367                         # skip if this record doesn't have this field
368                         next if not defined $record->field($field);
369                         if ($subfield) {
370                             $record->field($field)->delete_subfields($subfield);
371                         }
372                         else {
373                             $record->delete_field( $record->field($field) );
374                         }
375                     }
376                 }
377                 RemoveAllNsb($record) if ($clean);
378                 if ( $output_format eq "xml" ) {
379                     unless ($xml_header_written) {
380                         MARC::File::XML->default_record_format(
381                             (
382                                      $marcflavour eq 'UNIMARC'
383                                   && $record_type eq 'auths'
384                             ) ? 'UNIMARCAUTH' : $marcflavour
385                         );
386                         print MARC::File::XML::header();
387                         print "\n";
388                         $xml_header_written = 1;
389                     }
390                     print MARC::File::XML::record($record);
391                     print "\n";
392                 }
393                 else {
394                     print $record->as_usmarc();
395                 }
396             }
397         }
398         if ($xml_header_written) {
399             print MARC::File::XML::footer();
400             print "\n";
401         }
402
403         exit;
404     }
405     elsif ( $format eq "csv" ) {
406         my @biblionumbers = uniq $query->param("biblionumbers");
407         my @itemnumbers   = $query->param("itemnumbers");
408         my $output =
409           marc2csv( \@biblionumbers,
410             GetCsvProfileId( C4::Context->preference('ExportWithCsvProfile') ),
411             \@itemnumbers, );
412         print $query->header(
413             -type                        => 'application/octet-stream',
414             -'Content-Transfer-Encoding' => 'binary',
415             -attachment                  => "export.csv"
416         );
417         print $output;
418         exit;
419     }
420 }    # if export
421
422 else {
423
424     my $itemtypes = GetItemTypes;
425     my @itemtypesloop;
426     foreach my $thisitemtype ( sort keys %$itemtypes ) {
427         my %row = (
428             value       => $thisitemtype,
429             description => $itemtypes->{$thisitemtype}->{'description'},
430         );
431         push @itemtypesloop, \%row;
432     }
433     my $branches = GetBranches($limit_ind_branch);
434     my @branchloop;
435     for my $thisbranch (
436         sort { $branches->{$a}->{branchname} cmp $branches->{$b}->{branchname} }
437         keys %{$branches}
438       )
439     {
440         push @branchloop,
441           {
442             value      => $thisbranch,
443             selected   => $thisbranch eq $branch,
444             branchname => $branches->{$thisbranch}->{'branchname'},
445           };
446     }
447
448     my $authtypes = getauthtypes;
449     my @authtypesloop;
450     foreach my $thisauthtype ( sort keys %$authtypes ) {
451         next unless $thisauthtype;
452         my %row = (
453             value       => $thisauthtype,
454             description => $authtypes->{$thisauthtype}->{'authtypetext'},
455         );
456         push @authtypesloop, \%row;
457     }
458
459     if (   $flags->{superlibrarian}
460         && C4::Context->config('backup_db_via_tools')
461         && $backupdir
462         && -d $backupdir )
463     {
464         $template->{VARS}->{'allow_db_export'} = 1;
465         $template->{VARS}->{'dbfiles'}         = getbackupfilelist(
466             { directory => "$backupdir", extension => 'sql' } );
467     }
468
469     if (   $flags->{superlibrarian}
470         && C4::Context->config('backup_conf_via_tools')
471         && $backupdir
472         && -d $backupdir )
473     {
474         $template->{VARS}->{'allow_conf_export'} = 1;
475         $template->{VARS}->{'conffiles'}         = getbackupfilelist(
476             { directory => "$backupdir", extension => 'tar' } );
477     }
478
479     $template->param(
480         branchloop               => \@branchloop,
481         itemtypeloop             => \@itemtypesloop,
482         authtypeloop             => \@authtypesloop,
483         export_remove_fields     => C4::Context->preference("ExportRemoveFields"),
484     );
485
486     output_html_with_http_headers $query, $cookie, $template->output;
487 }
488
489 sub construct_query {
490     my ($params) = @_;
491
492     my ( $sql_query, @sql_params );
493
494     if ( $params->{recordtype} eq "bibs" ) {
495         if ( $params->{timestamp} ) {
496             my $biblioitemstable = $params->{biblioitemstable};
497             $sql_query = " (
498                 SELECT biblionumber
499                 FROM $biblioitemstable
500                   LEFT JOIN items USING(biblionumber)
501                 WHERE $biblioitemstable.timestamp >= ?
502                   OR items.timestamp >= ?
503             ) UNION (
504                 SELECT biblionumber
505                 FROM $biblioitemstable
506                   LEFT JOIN deleteditems USING(biblionumber)
507                 WHERE $biblioitemstable.timestamp >= ?
508                   OR deleteditems.timestamp >= ?
509             ) ";
510             my $ts = $timestamp->output('iso');
511             @sql_params = ( $ts, $ts, $ts, $ts );
512         }
513         else {
514             my $biblioitemstable     = $params->{biblioitemstable};
515             my $itemstable           = $params->{itemstable};
516             my $StartingBiblionumber = $params->{StartingBiblionumber};
517             my $EndingBiblionumber   = $params->{EndingBiblionumber};
518             my $branch               = $params->{branch};
519             my $start_callnumber     = $params->{start_callnumber};
520             my $end_callnumber       = $params->{end_callnumber};
521             my $start_accession      = $params->{start_accession};
522             my $end_accession        = $params->{end_accession};
523             my $itemtype             = $params->{itemtype};
524             my $items_filter =
525                  $branch
526               || $start_callnumber
527               || $end_callnumber
528               || $start_accession
529               || $end_accession
530               || ( $itemtype && C4::Context->preference('item-level_itypes') );
531             $sql_query = $items_filter
532               ? "SELECT DISTINCT $biblioitemstable.biblionumber
533                 FROM $biblioitemstable JOIN $itemstable
534                 USING (biblionumber) WHERE 1"
535               : "SELECT $biblioitemstable.biblionumber FROM $biblioitemstable WHERE biblionumber >0 ";
536
537             if ($StartingBiblionumber) {
538                 $sql_query .= " AND $biblioitemstable.biblionumber >= ? ";
539                 push @sql_params, $StartingBiblionumber;
540             }
541
542             if ($EndingBiblionumber) {
543                 $sql_query .= " AND $biblioitemstable.biblionumber <= ? ";
544                 push @sql_params, $EndingBiblionumber;
545             }
546
547             if ($branch) {
548                 $sql_query .= " AND homebranch = ? ";
549                 push @sql_params, $branch;
550             }
551
552             if ($start_callnumber) {
553                 $sql_query .= " AND itemcallnumber >= ? ";
554                 push @sql_params, $start_callnumber;
555             }
556
557             if ($end_callnumber) {
558                 $sql_query .= " AND itemcallnumber <= ? ";
559                 push @sql_params, $end_callnumber;
560             }
561             if ($start_accession) {
562                 $sql_query .= " AND dateaccessioned >= ? ";
563                 push @sql_params, $start_accession->output('iso');
564             }
565
566             if ($end_accession) {
567                 $sql_query .= " AND dateaccessioned <= ? ";
568                 push @sql_params, $end_accession->output('iso');
569             }
570
571             if ($itemtype) {
572                 $sql_query .=
573                   ( C4::Context->preference('item-level_itypes') )
574                   ? " AND items.itype = ? "
575                   : " AND biblioitems.itemtype = ?";
576                 push @sql_params, $itemtype;
577             }
578         }
579     }
580     elsif ( $params->{recordtype} eq "auths" ) {
581         if ( $params->{timestamp} ) {
582
583             #TODO
584         }
585         else {
586             my $starting_authid = $params->{starting_authid};
587             my $ending_authid   = $params->{ending_authid};
588             my $authtype        = $params->{authtype};
589             $sql_query =
590               "SELECT DISTINCT auth_header.authid FROM auth_header WHERE 1";
591
592             if ($starting_authid) {
593                 $sql_query .= " AND auth_header.authid >= ? ";
594                 push @sql_params, $starting_authid;
595             }
596
597             if ($ending_authid) {
598                 $sql_query .= " AND auth_header.authid <= ? ";
599                 push @sql_params, $ending_authid;
600             }
601
602             if ($authtype) {
603                 $sql_query .= " AND auth_header.authtypecode = ? ";
604                 push @sql_params, $authtype;
605             }
606         }
607     }
608     return ( $sql_query, \@sql_params );
609 }
610
611 sub getbackupfilelist {
612     my $args      = shift;
613     my $directory = $args->{directory};
614     my $extension = $args->{extension};
615     my @files;
616
617     if ( opendir( my $dir, $directory ) ) {
618         while ( my $file = readdir($dir) ) {
619             next unless ( $file =~ m/\.$extension(\.(gz|bz2|xz))?/ );
620             push @files, $file
621               if ( -f "$directory/$file" && -r "$directory/$file" );
622         }
623         closedir($dir);
624     }
625     return \@files;
626 }
627
628 sub download_backup {
629     my $args      = shift;
630     my $directory = $args->{directory};
631     my $extension = $args->{extension};
632     my $filename  = $args->{filename};
633
634     return unless ( $directory && -d $directory );
635     return unless ( $filename =~ m/\.$extension(\.(gz|bz2|xz))?$/ );
636     return if ( $filename =~ m#/# );
637     $filename = "$directory/$filename";
638     return unless ( -f $filename && -r $filename );
639     return unless ( open( my $dump, '<', $filename ) );
640     binmode $dump;
641
642     while ( read( $dump, my $data, 64 * 1024 ) ) {
643         print $data;
644     }
645     close($dump);
646     return 1;
647 }