Bug 22690: Refactor merging of records to improve performance (Elasticsearch)
[koha.git] / cataloguing / addbiblio.pl
1 #!/usr/bin/perl 
2
3
4 # Copyright 2000-2002 Katipo Communications
5 # Copyright 2004-2010 BibLibre
6 #
7 # This file is part of Koha.
8 #
9 # Koha is free software; you can redistribute it and/or modify it
10 # under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
13 #
14 # Koha is distributed in the hope that it will be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with Koha; if not, see <http://www.gnu.org/licenses>.
21
22 use Modern::Perl;
23
24 use CGI;
25 use C4::Output qw( output_html_with_http_headers );
26 use C4::Auth qw( get_template_and_user haspermission );
27 use C4::Biblio qw(
28     AddBiblio
29     DelBiblio
30     GetFrameworkCode
31     GetMarcBiblio
32     GetMarcFromKohaField
33     GetMarcStructure
34     GetUsedMarcStructure
35     ModBiblio
36     prepare_host_field
37     PrepHostMarcField
38     TransformHtmlToMarc
39 );
40 use C4::Search qw( FindDuplicate enabled_staff_search_views );
41 use C4::Auth qw( get_template_and_user haspermission );
42 use C4::Context;
43 use MARC::Record;
44 use C4::ClassSource qw( GetClassSources );
45 use C4::ImportBatch qw( GetImportRecordMarc );
46 use C4::Charset qw( SetMarcUnicodeFlag );
47 use Koha::BiblioFrameworks;
48 use Koha::DateUtils qw( dt_from_string );
49
50 use Koha::ItemTypes;
51 use Koha::Libraries;
52
53 use Koha::BiblioFrameworks;
54
55 use MARC::File::USMARC;
56 use MARC::File::XML;
57 use URI::Escape qw( uri_escape_utf8 );
58
59 if ( C4::Context->preference('marcflavour') eq 'UNIMARC' ) {
60     MARC::File::XML->default_record_format('UNIMARC');
61 }
62
63 our($tagslib,$authorised_values_sth,$is_a_modif,$usedTagsLib,$mandatory_z3950);
64
65 =head1 FUNCTIONS
66
67 =head2 MARCfindbreeding
68
69     $record = MARCfindbreeding($breedingid);
70
71 Look up the import record repository for the record with
72 record with id $breedingid.  If found, returns the decoded
73 MARC::Record; otherwise, -1 is returned (FIXME).
74 Returns as second parameter the character encoding.
75
76 =cut
77
78 sub MARCfindbreeding {
79     my ( $id ) = @_;
80     my ($marc, $encoding) = GetImportRecordMarc($id);
81     # remove the - in isbn, koha store isbn without any -
82     if ($marc) {
83         my $record = MARC::Record->new_from_usmarc($marc);
84         my ($isbnfield,$isbnsubfield) = GetMarcFromKohaField( 'biblioitems.isbn' );
85         if ( $record->field($isbnfield) ) {
86             foreach my $field ( $record->field($isbnfield) ) {
87                 foreach my $subfield ( $field->subfield($isbnsubfield) ) {
88                     my $newisbn = $field->subfield($isbnsubfield);
89                     $newisbn =~ s/-//g;
90                     $field->update( $isbnsubfield => $newisbn );
91                 }
92             }
93         }
94         # fix the unimarc 100 coded field (with unicode information)
95         if (C4::Context->preference('marcflavour') eq 'UNIMARC' && $record->subfield(100,'a')) {
96             my $f100a=$record->subfield(100,'a');
97             my $f100 = $record->field(100);
98             my $f100temp = $f100->as_string;
99             $record->delete_field($f100);
100             if ( length($f100temp) > 28 ) {
101                 substr( $f100temp, 26, 2, "50" );
102                 $f100->update( 'a' => $f100temp );
103                 my $f100 = MARC::Field->new( '100', '', '', 'a' => $f100temp );
104                 $record->insert_fields_ordered($f100);
105             }
106         }
107                 
108         if ( !defined(ref($record)) ) {
109             return -1;
110         }
111         else {
112             # normalize author : UNIMARC specific...
113             if (    C4::Context->preference("z3950NormalizeAuthor")
114                 and C4::Context->preference("z3950AuthorAuthFields")
115                 and C4::Context->preference("marcflavour") eq 'UNIMARC' )
116             {
117                 my ( $tag, $subfield ) = GetMarcFromKohaField( "biblio.author" );
118
119                 my $auth_fields =
120                   C4::Context->preference("z3950AuthorAuthFields");
121                 my @auth_fields = split /,/, $auth_fields;
122                 my $field;
123
124                 if ( $record->field($tag) ) {
125                     foreach my $tmpfield ( $record->field($tag)->subfields ) {
126
127                         my $subfieldcode  = shift @$tmpfield;
128                         my $subfieldvalue = shift @$tmpfield;
129                         if ($field) {
130                             $field->add_subfields(
131                                 "$subfieldcode" => $subfieldvalue )
132                               if ( $subfieldcode ne $subfield );
133                         }
134                         else {
135                             $field =
136                               MARC::Field->new( $tag, "", "",
137                                 $subfieldcode => $subfieldvalue )
138                               if ( $subfieldcode ne $subfield );
139                         }
140                     }
141                 }
142                 $record->delete_field( $record->field($tag) );
143                 foreach my $fieldtag (@auth_fields) {
144                     next unless ( $record->field($fieldtag) );
145                     my $lastname  = $record->field($fieldtag)->subfield('a');
146                     my $firstname = $record->field($fieldtag)->subfield('b');
147                     my $title     = $record->field($fieldtag)->subfield('c');
148                     my $number    = $record->field($fieldtag)->subfield('d');
149                     if ($title) {
150                         $field->add_subfields(
151                                 "$subfield" => ucfirst($title) . " "
152                               . ucfirst($firstname) . " "
153                               . $number );
154                     }
155                     else {
156                         $field->add_subfields(
157                             "$subfield" => ucfirst($firstname) . ", "
158                               . ucfirst($lastname) );
159                     }
160                 }
161                 $record->insert_fields_ordered($field);
162             }
163             return $record, $encoding;
164         }
165     }
166     return -1;
167 }
168
169 =head2 build_authorized_values_list
170
171 =cut
172
173 sub build_authorized_values_list {
174     my ( $tag, $subfield, $value, $dbh, $authorised_values_sth,$index_tag,$index_subfield ) = @_;
175
176     my @authorised_values;
177     my %authorised_lib;
178
179     # builds list, depending on authorised value...
180
181     #---- branch
182     my $category = $tagslib->{$tag}->{$subfield}->{authorised_value};
183     if ( $category eq "branches" ) {
184         my $libraries = Koha::Libraries->search_filtered({}, {order_by => ['branchname']});
185         while ( my $l = $libraries->next ) {
186             push @authorised_values, $l->branchcode;;
187             $authorised_lib{$l->branchcode} = $l->branchname;
188         }
189     }
190     elsif ( $category eq "itemtypes" ) {
191         push @authorised_values, "";
192
193         my $itemtype;
194         my $itemtypes = Koha::ItemTypes->search_with_localization;
195         while ( $itemtype = $itemtypes->next ) {
196             push @authorised_values, $itemtype->itemtype;
197             $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description;
198         }
199         $value = $itemtype unless ($value);
200     }
201     elsif ( $category eq "cn_source" ) {
202         push @authorised_values, "";
203
204         my $class_sources = GetClassSources();
205
206         my $default_source = C4::Context->preference("DefaultClassificationSource");
207
208         foreach my $class_source (sort keys %$class_sources) {
209             next unless $class_sources->{$class_source}->{'used'} or
210                         ($value and $class_source eq $value) or
211                         ($class_source eq $default_source);
212             push @authorised_values, $class_source;
213             $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
214         }
215         $value = $default_source unless $value;
216     }
217     else {
218         my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
219         $authorised_values_sth->execute(
220             $tagslib->{$tag}->{$subfield}->{authorised_value},
221             $branch_limit ? $branch_limit : (),
222         );
223
224         push @authorised_values, "";
225
226         while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
227             push @authorised_values, $value;
228             $authorised_lib{$value} = $lib;
229         }
230     }
231     $authorised_values_sth->finish;
232
233     return {
234         type     => 'select',
235         id       => "tag_".$tag."_subfield_".$subfield."_".$index_tag."_".$index_subfield,
236         name     => "tag_".$tag."_subfield_".$subfield."_".$index_tag."_".$index_subfield,
237         default  => $value,
238         values   => \@authorised_values,
239         labels   => \%authorised_lib,
240         ( ( grep { $_ eq $category } ( qw(branches itemtypes cn_source) ) ) ? () : ( category => $category ) ),
241     };
242
243 }
244
245 =head2 CreateKey
246
247     Create a random value to set it into the input name
248
249 =cut
250
251 sub CreateKey {
252     return int(rand(1000000));
253 }
254
255 =head2 GetMandatoryFieldZ3950
256
257     This function returns a hashref which contains all mandatory field
258     to search with z3950 server.
259
260 =cut
261
262 sub GetMandatoryFieldZ3950 {
263     my $frameworkcode = shift;
264     my @isbn   = GetMarcFromKohaField( 'biblioitems.isbn' );
265     my @title  = GetMarcFromKohaField( 'biblio.title' );
266     my @author = GetMarcFromKohaField( 'biblio.author' );
267     my @issn   = GetMarcFromKohaField( 'biblioitems.issn' );
268     my @lccn   = GetMarcFromKohaField( 'biblioitems.lccn' );
269     
270     return {
271         $isbn[0].$isbn[1]     => 'isbn',
272         $title[0].$title[1]   => 'title',
273         $author[0].$author[1] => 'author',
274         $issn[0].$issn[1]     => 'issn',
275         $lccn[0].$lccn[1]     => 'lccn',
276     };
277 }
278
279 =head2 create_input
280
281  builds the <input ...> entry for a subfield.
282
283 =cut
284
285 sub create_input {
286     my ( $tag, $subfield, $value, $index_tag, $tabloop, $rec, $authorised_values_sth,$cgi ) = @_;
287     
288     my $index_subfield = CreateKey(); # create a specifique key for each subfield
289
290     # if there is no value provided but a default value in parameters, get it
291     if ( $value eq '' ) {
292         $value = $tagslib->{$tag}->{$subfield}->{defaultvalue} // q{};
293
294         # get today date & replace <<YYYY>>, <<YY>>, <<MM>>, <<DD>> if provided in the default value
295         my $today_dt = dt_from_string;
296         my $year = $today_dt->strftime('%Y');
297         my $shortyear = $today_dt->strftime('%y');
298         my $month = $today_dt->strftime('%m');
299         my $day = $today_dt->strftime('%d');
300         $value =~ s/<<YYYY>>/$year/g;
301         $value =~ s/<<YY>>/$shortyear/g;
302         $value =~ s/<<MM>>/$month/g;
303         $value =~ s/<<DD>>/$day/g;
304         # And <<USER>> with surname (?)
305         my $username=(C4::Context->userenv?C4::Context->userenv->{'surname'}:"superlibrarian");
306         $value=~s/<<USER>>/$username/g;
307     
308     }
309     my $dbh = C4::Context->dbh;
310
311     # map '@' as "subfield" label for fixed fields
312     # to something that's allowed in a div id.
313     my $id_subfield = $subfield;
314     $id_subfield = "00" if $id_subfield eq "@";
315
316     my %subfield_data = (
317         tag        => $tag,
318         subfield   => $id_subfield,
319         marc_lib       => $tagslib->{$tag}->{$subfield}->{lib},
320         tag_mandatory  => $tagslib->{$tag}->{mandatory},
321         mandatory      => $tagslib->{$tag}->{$subfield}->{mandatory},
322         important      => $tagslib->{$tag}->{$subfield}->{important},
323         repeatable     => $tagslib->{$tag}->{$subfield}->{repeatable},
324         kohafield      => $tagslib->{$tag}->{$subfield}->{kohafield},
325         index          => $index_tag,
326         id             => "tag_".$tag."_subfield_".$id_subfield."_".$index_tag."_".$index_subfield,
327         value          => $value,
328         maxlength      => $tagslib->{$tag}->{$subfield}->{maxlength},
329         random         => CreateKey(),
330     );
331
332     if(exists $mandatory_z3950->{$tag.$subfield}){
333         $subfield_data{z3950_mandatory} = $mandatory_z3950->{$tag.$subfield};
334     }
335     # Subfield is hidden depending of hidden and mandatory flag, and is always
336     # shown if it contains anything or if its field is mandatory or important.
337     my $tdef = $tagslib->{$tag};
338     $subfield_data{visibility} = "display:none;"
339         if $tdef->{$subfield}->{hidden} % 2 == 1 &&
340            $value eq '' &&
341            !$tdef->{$subfield}->{mandatory} &&
342            !$tdef->{mandatory} &&
343            !$tdef->{$subfield}->{important} &&
344            !$tdef->{important};
345     # expand all subfields of 773 if there is a host item provided in the input
346     $subfield_data{visibility} ="" if ($tag eq 773 and $cgi->param('hostitemnumber'));
347
348
349     # it's an authorised field
350     if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
351         $subfield_data{marc_value} =
352           build_authorized_values_list( $tag, $subfield, $value, $dbh,
353             $authorised_values_sth,$index_tag,$index_subfield );
354
355     # it's a subfield $9 linking to an authority record - see bug 2206
356     }
357     elsif ($subfield eq "9" and
358            exists($tagslib->{$tag}->{'a'}->{authtypecode}) and
359            defined($tagslib->{$tag}->{'a'}->{authtypecode}) and
360            $tagslib->{$tag}->{'a'}->{authtypecode} ne '') {
361
362         $subfield_data{marc_value} = {
363             type      => 'text',
364             id        => $subfield_data{id},
365             name      => $subfield_data{id},
366             value     => $value,
367             size      => 5,
368             maxlength => $subfield_data{maxlength},
369             readonly  => 1,
370         };
371
372     # it's a thesaurus / authority field
373     }
374     elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode} ) {
375         # when authorities auto-creation is allowed, do not set readonly
376         my $is_readonly = !C4::Context->preference("BiblioAddsAuthorities");
377
378         $subfield_data{marc_value} = {
379             type      => 'text',
380             id        => $subfield_data{id},
381             name      => $subfield_data{id},
382             value     => $value,
383             size      => 67,
384             maxlength => $subfield_data{maxlength},
385             readonly  => ($is_readonly) ? 1 : 0,
386             authtype  => $tagslib->{$tag}->{$subfield}->{authtypecode},
387         };
388
389     # it's a plugin field
390     } elsif ( $tagslib->{$tag}->{$subfield}->{'value_builder'} ) {
391         require Koha::FrameworkPlugin;
392         my $plugin = Koha::FrameworkPlugin->new( {
393             name => $tagslib->{$tag}->{$subfield}->{'value_builder'},
394         });
395         my $pars= { dbh => $dbh, record => $rec, tagslib => $tagslib,
396             id => $subfield_data{id}, tabloop => $tabloop };
397         $plugin->build( $pars );
398         if( !$plugin->errstr ) {
399             $subfield_data{marc_value} = {
400                 type           => 'text_complex',
401                 id             => $subfield_data{id},
402                 name           => $subfield_data{id},
403                 value          => $value,
404                 size           => 67,
405                 maxlength      => $subfield_data{maxlength},
406                 javascript     => $plugin->javascript,
407                 plugin         => $plugin->name,
408                 noclick        => $plugin->noclick,
409             };
410         } else {
411             warn $plugin->errstr;
412             # supply default input form
413             $subfield_data{marc_value} = {
414                 type      => 'text',
415                 id        => $subfield_data{id},
416                 name      => $subfield_data{id},
417                 value     => $value,
418                 size      => 67,
419                 maxlength => $subfield_data{maxlength},
420                 readonly  => 0,
421             };
422         }
423
424     # it's an hidden field
425     } elsif ( $tag eq '' ) {
426         $subfield_data{marc_value} = {
427             type      => 'hidden',
428             id        => $subfield_data{id},
429             name      => $subfield_data{id},
430             value     => $value,
431             size      => 67,
432             maxlength => $subfield_data{maxlength},
433         };
434
435     }
436     else {
437         # it's a standard field
438         if (
439             length($value) > 100
440             or
441             ( C4::Context->preference("marcflavour") eq "UNIMARC" && $tag >= 300
442                 and $tag < 400 && $subfield eq 'a' )
443             or (    $tag >= 500
444                 and $tag < 600
445                 && C4::Context->preference("marcflavour") eq "MARC21" )
446           )
447         {
448             $subfield_data{marc_value} = {
449                 type      => 'textarea',
450                 id        => $subfield_data{id},
451                 name      => $subfield_data{id},
452                 value     => $value,
453             };
454
455         }
456         else {
457             $subfield_data{marc_value} = {
458                 type      => 'text',
459                 id        => $subfield_data{id},
460                 name      => $subfield_data{id},
461                 value     => $value,
462                 size      => 67,
463                 maxlength => $subfield_data{maxlength},
464                 readonly  => 0,
465             };
466
467         }
468     }
469     $subfield_data{'index_subfield'} = $index_subfield;
470     return \%subfield_data;
471 }
472
473
474 =head2 format_indicator
475
476 Translate indicator value for output form - specifically, map
477 indicator = ' ' to ''.  This is for the convenience of a cataloger
478 using a mouse to select an indicator input.
479
480 =cut
481
482 sub format_indicator {
483     my $ind_value = shift;
484     return '' if not defined $ind_value;
485     return '' if $ind_value eq ' ';
486     return $ind_value;
487 }
488
489 sub build_tabs {
490     my ( $template, $record, $dbh, $encoding,$input ) = @_;
491
492     # fill arrays
493     my @loop_data = ();
494     my $tag;
495
496     my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
497     my $query = "SELECT authorised_value, lib
498                 FROM authorised_values";
499     $query .= qq{ LEFT JOIN authorised_values_branches ON ( id = av_id )} if $branch_limit;
500     $query .= " WHERE category = ?";
501     $query .= " AND ( branchcode = ? OR branchcode IS NULL )" if $branch_limit;
502     $query .= " GROUP BY authorised_value,lib ORDER BY lib, lib_opac";
503     my $authorised_values_sth = $dbh->prepare( $query );
504
505     # in this array, we will push all the 10 tabs
506     # to avoid having 10 tabs in the template : they will all be in the same BIG_LOOP
507     my @BIG_LOOP;
508     my %seen;
509     my @tab_data; # all tags to display
510
511     my $max_num_tab=-1;
512     my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField( "items.itemnumber" );
513     foreach my $used ( @$usedTagsLib ){
514
515         push @tab_data,$used->{tagfield} if not $seen{$used->{tagfield}};
516         $seen{$used->{tagfield}}++;
517
518         if (   $used->{tab} > -1
519             && $used->{tab} >= $max_num_tab
520             && $used->{tagfield} ne $itemtag )
521         {
522             $max_num_tab = $used->{tab};
523         }
524     }
525     if($max_num_tab >= 9){
526         $max_num_tab = 9;
527     }
528     # loop through each tab 0 through 9
529     for ( my $tabloop = 0 ; $tabloop <= $max_num_tab ; $tabloop++ ) {
530         my @loop_data = (); #innerloop in the template.
531         my $i = 0;
532         foreach my $tag (sort @tab_data) {
533             $i++;
534             next if ! $tag;
535             my ($indicator1, $indicator2);
536             my $index_tag = CreateKey;
537
538             # if MARC::Record is not empty =>use it as master loop, then add missing subfields that should be in the tab.
539             # if MARC::Record is empty => use tab as master loop.
540             if ( $record ne -1 && ( $record->field($tag) || $tag eq '000' ) ) {
541                 my @fields;
542                 if ( $tag ne '000' ) {
543                     @fields = $record->field($tag);
544                 }
545                 else {
546                    push @fields, $record->leader(); # if tag == 000
547                 }
548                 # loop through each field
549                 foreach my $field (@fields) {
550                     
551                     my @subfields_data;
552                     if ( $tag < 10 ) {
553                         my ( $value, $subfield );
554                         if ( $tag ne '000' ) {
555                             $value    = $field->data();
556                             $subfield = "@";
557                         }
558                         else {
559                             $value    = $field;
560                             $subfield = '@';
561                         }
562                         next if ( $tagslib->{$tag}->{$subfield}->{tab} ne $tabloop );
563                         next
564                           if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq
565                             'biblio.biblionumber' );
566                         push(
567                             @subfields_data,
568                             &create_input(
569                                 $tag, $subfield, $value, $index_tag, $tabloop, $record,
570                                 $authorised_values_sth,$input
571                             )
572                         );
573                     }
574                     else {
575                         my @subfields = $field->subfields();
576                         foreach my $subfieldcount ( 0 .. $#subfields ) {
577                             my $subfield = $subfields[$subfieldcount][0];
578                             my $value    = $subfields[$subfieldcount][1];
579                             next if ( length $subfield != 1 );
580                             next if ( !defined $tagslib->{$tag}->{$subfield} || $tagslib->{$tag}->{$subfield}->{tab} ne $tabloop );
581                             push(
582                                 @subfields_data,
583                                 &create_input(
584                                     $tag, $subfield, $value, $index_tag, $tabloop,
585                                     $record, $authorised_values_sth,$input
586                                 )
587                             );
588                         }
589                     }
590
591                     # now, loop again to add parameter subfield that are not in the MARC::Record
592                     foreach my $subfield ( keys %{ $tagslib->{$tag} } )
593                     {
594                         next if ( length $subfield != 1 );
595                         next if ( $tagslib->{$tag}->{$subfield}->{tab} ne $tabloop );
596                         next if ( $tag < 10 );
597                         next
598                           if ( ( $tagslib->{$tag}->{$subfield}->{hidden} <= -4 )
599                             or ( $tagslib->{$tag}->{$subfield}->{hidden} >= 5 ) )
600                             and not ( $subfield eq "9" and
601                                       exists($tagslib->{$tag}->{'a'}->{authtypecode}) and
602                                       defined($tagslib->{$tag}->{'a'}->{authtypecode}) and
603                                       $tagslib->{$tag}->{'a'}->{authtypecode} ne ""
604                                     )
605                           ;    #check for visibility flag
606                                # if subfield is $9 in a field whose $a is authority-controlled,
607                                # always include in the form regardless of the hidden setting - bug 2206
608                         next if ( defined( $field->subfield($subfield) ) );
609                         push(
610                             @subfields_data,
611                             &create_input(
612                                 $tag, $subfield, '', $index_tag, $tabloop, $record,
613                                 $authorised_values_sth,$input
614                             )
615                         );
616                     }
617                     if ( $#subfields_data >= 0 ) {
618                         # build the tag entry.
619                         # note that the random() field is mandatory. Otherwise, on repeated fields, you'll 
620                         # have twice the same "name" value, and cgi->param() will return only one, making
621                         # all subfields to be merged in a single field.
622                         my %tag_data = (
623                             tag           => $tag,
624                             index         => $index_tag,
625                             tag_lib       => $tagslib->{$tag}->{lib},
626                             repeatable       => $tagslib->{$tag}->{repeatable},
627                             mandatory       => $tagslib->{$tag}->{mandatory},
628                             important       => $tagslib->{$tag}->{important},
629                             subfield_loop => \@subfields_data,
630                             fixedfield    => $tag < 10?1:0,
631                             random        => CreateKey,
632                         );
633                         if ($tag >= 10){ # no indicator for 00x tags
634                            $tag_data{indicator1} = format_indicator($field->indicator(1)),
635                            $tag_data{indicator2} = format_indicator($field->indicator(2)),
636                         }
637                         push( @loop_data, \%tag_data );
638                     }
639                  } # foreach $field end
640
641             # if breeding is empty
642             }
643             else {
644                 my @subfields_data;
645                 foreach my $subfield (
646                     sort { $a->{display_order} <=> $b->{display_order} || $a->{subfield} cmp $b->{subfield} }
647                     grep { ref($_) && %$_ } # Not a subfield (values for "important", "lib", "mandatory", etc.) or empty
648                     values %{ $tagslib->{$tag} } )
649                 {
650                     next
651                       if ( ( $subfield->{hidden} <= -4 )
652                         or ( $subfield->{hidden} >= 5 ) )
653                       and not ( $subfield->{subfield} eq "9" and
654                                 exists($tagslib->{$tag}->{'a'}->{authtypecode}) and
655                                 defined($tagslib->{$tag}->{'a'}->{authtypecode}) and
656                                 $tagslib->{$tag}->{'a'}->{authtypecode} ne ""
657                               )
658                       ;    #check for visibility flag
659                            # if subfield is $9 in a field whose $a is authority-controlled,
660                            # always include in the form regardless of the hidden setting - bug 2206
661                     next
662                       if ( $subfield->{tab} ne $tabloop );
663                         push(
664                         @subfields_data,
665                         &create_input(
666                             $tag, $subfield->{subfield}, '', $index_tag, $tabloop, $record,
667                             $authorised_values_sth,$input
668                         )
669                     );
670                 }
671                 if ( $#subfields_data >= 0 ) {
672                     my %tag_data = (
673                         tag              => $tag,
674                         index            => $index_tag,
675                         tag_lib          => $tagslib->{$tag}->{lib},
676                         repeatable       => $tagslib->{$tag}->{repeatable},
677                         mandatory       => $tagslib->{$tag}->{mandatory},
678                         important       => $tagslib->{$tag}->{important},
679                         indicator1       => ( $indicator1 || $tagslib->{$tag}->{ind1_defaultvalue} ), #if not set, try to load the default value
680                         indicator2       => ( $indicator2 || $tagslib->{$tag}->{ind2_defaultvalue} ), #use short-circuit operator for efficiency
681                         subfield_loop    => \@subfields_data,
682                         tagfirstsubfield => $subfields_data[0],
683                         fixedfield       => $tag < 10?1:0,
684                     );
685                     
686                     push @loop_data, \%tag_data ;
687                 }
688             }
689         }
690         if ( $#loop_data >= 0 ) {
691             push @BIG_LOOP, {
692                 number    => $tabloop,
693                 innerloop => \@loop_data,
694             };
695         }
696     }
697     $authorised_values_sth->finish;
698     $template->param( BIG_LOOP => \@BIG_LOOP );
699 }
700
701 # ========================
702 #          MAIN
703 #=========================
704 my $input = CGI->new;
705 my $error = $input->param('error');
706 my $biblionumber  = $input->param('biblionumber'); # if biblionumber exists, it's a modif, not a new biblio.
707 my $parentbiblio  = $input->param('parentbiblionumber');
708 my $breedingid    = $input->param('breedingid');
709 my $z3950         = $input->param('z3950');
710 my $op            = $input->param('op') // q{};
711 my $mode          = $input->param('mode');
712 my $frameworkcode = $input->param('frameworkcode');
713 my $redirect      = $input->param('redirect');
714 my $searchid      = $input->param('searchid') // "";
715 my $dbh           = C4::Context->dbh;
716 my $hostbiblionumber = $input->param('hostbiblionumber');
717 my $hostitemnumber = $input->param('hostitemnumber');
718 # fast cataloguing datas in transit
719 my $fa_circborrowernumber = $input->param('circborrowernumber');
720 my $fa_barcode            = $input->param('barcode');
721 my $fa_branch             = $input->param('branch');
722 my $fa_stickyduedate      = $input->param('stickyduedate');
723 my $fa_duedatespec        = $input->param('duedatespec');
724
725 my $userflags = 'edit_catalogue';
726
727 my $changed_framework = $input->param('changed_framework') // q{};
728 $frameworkcode = &GetFrameworkCode($biblionumber)
729   if ( $biblionumber and not( defined $frameworkcode) and $op ne 'addbiblio' );
730
731 if ($frameworkcode eq 'FA'){
732     $userflags = 'fast_cataloging';
733 }
734
735 $frameworkcode = '' if ( $frameworkcode eq 'Default' );
736 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
737     {
738         template_name   => "cataloguing/addbiblio.tt",
739         query           => $input,
740         type            => "intranet",
741         flagsrequired   => { editcatalogue => $userflags },
742     }
743 );
744
745 if ($biblionumber){
746     my $does_bib_exist = Koha::Biblios->find($biblionumber);
747     if (!defined $does_bib_exist){
748         $biblionumber = undef;
749         $template->param( bib_doesnt_exist => 1 );
750     }
751 }
752
753 if ($frameworkcode eq 'FA'){
754     # We need to grab and set some variables in the template for use on the additems screen
755     $template->param(
756         'circborrowernumber' => $fa_circborrowernumber,
757         'barcode'            => $fa_barcode,
758         'branch'             => $fa_branch,
759         'stickyduedate'      => $fa_stickyduedate,
760         'duedatespec'        => $fa_duedatespec,
761     );
762 } elsif ( $op ne "delete" &&
763             C4::Context->preference('EnableAdvancedCatalogingEditor') &&
764             C4::Auth::haspermission(C4::Context->userenv->{id},{'editcatalogue'=>'advanced_editor'}) &&
765             $input->cookie( 'catalogue_editor_' . $loggedinuser ) eq 'advanced' &&
766             !$breedingid ) {
767     # Only use the advanced editor for non-fast-cataloging.
768     # breedingid is not handled because those would only come off a Z39.50
769     # search initiated by the basic editor.
770     print $input->redirect( '/cgi-bin/koha/cataloguing/editor.pl' . ( $biblionumber ? ( ($op eq 'duplicate'?'#duplicate/':'#catalog/') . $biblionumber ) : '' ) );
771     exit;
772 }
773
774 my $frameworks = Koha::BiblioFrameworks->search({}, { order_by => ['frameworktext'] });
775 $template->param(
776     frameworks => $frameworks,
777     breedingid => $breedingid,
778 );
779
780 # ++ Global
781 $tagslib         = &GetMarcStructure( 1, $frameworkcode );
782 $usedTagsLib     = &GetUsedMarcStructure( $frameworkcode );
783 $mandatory_z3950 = GetMandatoryFieldZ3950($frameworkcode);
784 # -- Global
785
786 my $record   = -1;
787 my $encoding = "";
788 my (
789         $biblionumbertagfield,
790         $biblionumbertagsubfield,
791         $biblioitemnumtagfield,
792         $biblioitemnumtagsubfield,
793         $biblioitemnumber
794 );
795
796 if (($biblionumber) && !($breedingid)){
797     $record = GetMarcBiblio({ biblionumber => $biblionumber });
798 }
799 if ($breedingid) {
800     ( $record, $encoding ) = MARCfindbreeding( $breedingid ) ;
801 }
802
803 #populate hostfield if hostbiblionumber is available
804 if ($hostbiblionumber) {
805     my $marcflavour = C4::Context->preference("marcflavour");
806     $record = MARC::Record->new();
807     $record->leader('');
808     my $field =
809       PrepHostMarcField( $hostbiblionumber, $hostitemnumber, $marcflavour );
810     $record->append_fields($field);
811 }
812
813 # This is  a child record
814 if ($parentbiblio) {
815     my $marcflavour = C4::Context->preference('marcflavour');
816     $record = MARC::Record->new();
817     SetMarcUnicodeFlag($record, $marcflavour);
818     my $hostfield = prepare_host_field($parentbiblio,$marcflavour);
819     if ($hostfield) {
820         $record->append_fields($hostfield);
821     }
822 }
823
824 $is_a_modif = 0;
825
826 if ($biblionumber) {
827     $is_a_modif = 1;
828     my $title = C4::Context->preference('marcflavour') eq "UNIMARC" ? $record->subfield('200', 'a') : $record->title;
829     $template->param( title => $title );
830
831     # if it's a modif, retrieve bibli and biblioitem numbers for the future modification of old-DB.
832     ( $biblionumbertagfield, $biblionumbertagsubfield ) =
833         &GetMarcFromKohaField( "biblio.biblionumber" );
834     ( $biblioitemnumtagfield, $biblioitemnumtagsubfield ) =
835         &GetMarcFromKohaField( "biblioitems.biblioitemnumber" );
836
837     # search biblioitems value
838     my $sth =  $dbh->prepare("select biblioitemnumber from biblioitems where biblionumber=?");
839     $sth->execute($biblionumber);
840     ($biblioitemnumber) = $sth->fetchrow;
841 }
842
843 #-------------------------------------------------------------------------------------
844 if ( $op eq "addbiblio" ) {
845 #-------------------------------------------------------------------------------------
846     $template->param(
847         biblionumberdata => $biblionumber,
848     );
849     # getting html input
850     my @params = $input->multi_param();
851     $record = TransformHtmlToMarc( $input, 1 );
852     # check for a duplicate
853     my ( $duplicatebiblionumber, $duplicatetitle );
854     if ( !$is_a_modif ) {
855         ( $duplicatebiblionumber, $duplicatetitle ) = FindDuplicate($record);
856     }
857     my $confirm_not_duplicate = $input->param('confirm_not_duplicate');
858     # it is not a duplicate (determined either by Koha itself or by user checking it's not a duplicate)
859     if ( !$duplicatebiblionumber or $confirm_not_duplicate ) {
860         my $oldbibitemnum;
861         if ( $is_a_modif ) {
862             ModBiblio( $record, $biblionumber, $frameworkcode );
863         }
864         else {
865             ( $biblionumber, $oldbibitemnum ) = AddBiblio( $record, $frameworkcode );
866         }
867         if ($redirect eq "items" || ($mode ne "popup" && !$is_a_modif && $redirect ne "view" && $redirect ne "just_save")){
868             if ($frameworkcode eq 'FA'){
869                 print $input->redirect(
870             '/cgi-bin/koha/cataloguing/additem.pl?'
871             .'biblionumber='.$biblionumber
872             .'&frameworkcode='.$frameworkcode
873             .'&circborrowernumber='.$fa_circborrowernumber
874             .'&branch='.$fa_branch
875             .'&barcode='.uri_escape_utf8($fa_barcode)
876             .'&stickyduedate='.$fa_stickyduedate
877             .'&duedatespec='.$fa_duedatespec
878                 );
879                 exit;
880             }
881             else {
882                 print $input->redirect(
883                 "/cgi-bin/koha/cataloguing/additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid"
884                 );
885                 exit;
886             }
887         }
888     elsif(($is_a_modif || $redirect eq "view") && $redirect ne "just_save"){
889             my $defaultview = C4::Context->preference('IntranetBiblioDefaultView');
890             my $views = { C4::Search::enabled_staff_search_views };
891             if ($defaultview eq 'isbd' && $views->{can_view_ISBD}) {
892                 print $input->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
893             } elsif  ($defaultview eq 'marc' && $views->{can_view_MARC}) {
894                 print $input->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid");
895             } elsif  ($defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC}) {
896                 print $input->redirect("/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
897             } else {
898                 print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber&searchid=$searchid");
899             }
900             exit;
901
902     }
903     elsif ($redirect eq "just_save"){
904         my $tab = $input->param('current_tab');
905         print $input->redirect("/cgi-bin/koha/cataloguing/addbiblio.pl?biblionumber=$biblionumber&framework=$frameworkcode&tab=$tab&searchid=$searchid");
906     }
907     else {
908           $template->param(
909             biblionumber => $biblionumber,
910             done         =>1,
911             popup        =>1
912           );
913           if ( $record ne '-1' ) {
914               my $title = C4::Context->preference('marcflavour') eq "UNIMARC" ? $record->subfield('200', 'a') : $record->title;
915               $template->param( title => $title );
916           }
917           $template->param(
918             popup => $mode,
919             itemtype => $frameworkcode,
920           );
921           output_html_with_http_headers $input, $cookie, $template->output;
922           exit;     
923         }
924     } else {
925     # it may be a duplicate, warn the user and do nothing
926         build_tabs ($template, $record, $dbh,$encoding,$input);
927         $template->param(
928             biblionumber             => $biblionumber,
929             biblioitemnumber         => $biblioitemnumber,
930             duplicatebiblionumber    => $duplicatebiblionumber,
931             duplicatebibid           => $duplicatebiblionumber,
932             duplicatetitle           => $duplicatetitle,
933         );
934     }
935 }
936 elsif ( $op eq "delete" ) {
937     
938     my $error = &DelBiblio($biblionumber);
939     if ($error) {
940         warn "ERROR when DELETING BIBLIO $biblionumber : $error";
941         print "Content-Type: text/html\n\n<html><body><h1>ERROR when DELETING BIBLIO $biblionumber : $error</h1></body></html>";
942         exit;
943     }
944     
945     print $input->redirect('/cgi-bin/koha/catalogue/search.pl' . ($searchid ? "?searchid=$searchid" : ""));
946     exit;
947     
948 } else {
949    #----------------------------------------------------------------------------
950    # If we're in a duplication case, we have to set to "" the biblionumber
951    # as we'll save the biblio as a new one.
952     $template->param(
953         biblionumberdata => $biblionumber,
954         op               => $op,
955     );
956     if ( $op eq "duplicate" ) {
957         $biblionumber = "";
958     }
959
960     if($changed_framework eq "changed"){
961         $record = TransformHtmlToMarc( $input, 1 );
962     }
963     elsif( $record ne -1 ) {
964 #FIXME: it's kind of silly to go from MARC::Record to MARC::File::XML and then back again just to fix the encoding
965         eval {
966             my $uxml = $record->as_xml;
967             MARC::Record::default_record_format("UNIMARC")
968             if ( C4::Context->preference("marcflavour") eq "UNIMARC" );
969             my $urecord = MARC::Record::new_from_xml( $uxml, 'UTF-8' );
970             $record = $urecord;
971         };
972     }
973     build_tabs( $template, $record, $dbh, $encoding,$input );
974     $template->param(
975         biblionumber             => $biblionumber,
976         biblionumbertagfield        => $biblionumbertagfield,
977         biblionumbertagsubfield     => $biblionumbertagsubfield,
978         biblioitemnumtagfield    => $biblioitemnumtagfield,
979         biblioitemnumtagsubfield => $biblioitemnumtagsubfield,
980         biblioitemnumber         => $biblioitemnumber,
981         hostbiblionumber        => $hostbiblionumber,
982         hostitemnumber          => $hostitemnumber
983     );
984 }
985
986 if ( $record ne '-1' ) {
987     my $title = C4::Context->preference('marcflavour') eq "UNIMARC" ? $record->subfield('200', 'a') : $record->title;
988     $template->param( title => $title );
989 }
990 $template->param(
991     popup => $mode,
992     frameworkcode => $frameworkcode,
993     itemtype => $frameworkcode,
994     borrowernumber => $loggedinuser,
995     tab => scalar $input->param('tab')
996 );
997 $template->{'VARS'}->{'searchid'} = $searchid;
998
999 output_html_with_http_headers $input, $cookie, $template->output;