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