Bug 27526: Fix 'add & duplicate item'
[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 and 28022
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 '' and
361            $tagslib->{$tag}->{'a'}->{hidden} > -4 and
362            $tagslib->{$tag}->{'a'}->{hidden} < 5) {
363         $subfield_data{marc_value} = {
364             type      => 'text',
365             id        => $subfield_data{id},
366             name      => $subfield_data{id},
367             value     => $value,
368             size      => 5,
369             maxlength => $subfield_data{maxlength},
370             readonly  => 1,
371         };
372
373     # it's a thesaurus / authority field
374     }
375     elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode} ) {
376         # when authorities auto-creation is allowed, do not set readonly
377         my $is_readonly = !C4::Context->preference("BiblioAddsAuthorities");
378
379         $subfield_data{marc_value} = {
380             type      => 'text',
381             id        => $subfield_data{id},
382             name      => $subfield_data{id},
383             value     => $value,
384             size      => 67,
385             maxlength => $subfield_data{maxlength},
386             readonly  => ($is_readonly) ? 1 : 0,
387             authtype  => $tagslib->{$tag}->{$subfield}->{authtypecode},
388         };
389
390     # it's a plugin field
391     } elsif ( $tagslib->{$tag}->{$subfield}->{'value_builder'} ) {
392         require Koha::FrameworkPlugin;
393         my $plugin = Koha::FrameworkPlugin->new( {
394             name => $tagslib->{$tag}->{$subfield}->{'value_builder'},
395         });
396         my $pars= { dbh => $dbh, record => $rec, tagslib => $tagslib,
397             id => $subfield_data{id}, tabloop => $tabloop };
398         $plugin->build( $pars );
399         if( !$plugin->errstr ) {
400             $subfield_data{marc_value} = {
401                 type           => 'text_complex',
402                 id             => $subfield_data{id},
403                 name           => $subfield_data{id},
404                 value          => $value,
405                 size           => 67,
406                 maxlength      => $subfield_data{maxlength},
407                 javascript     => $plugin->javascript,
408                 plugin         => $plugin->name,
409                 noclick        => $plugin->noclick,
410             };
411         } else {
412             warn $plugin->errstr;
413             # supply default input form
414             $subfield_data{marc_value} = {
415                 type      => 'text',
416                 id        => $subfield_data{id},
417                 name      => $subfield_data{id},
418                 value     => $value,
419                 size      => 67,
420                 maxlength => $subfield_data{maxlength},
421                 readonly  => 0,
422             };
423         }
424
425     # it's an hidden field
426     } elsif ( $tag eq '' ) {
427         $subfield_data{marc_value} = {
428             type      => 'hidden',
429             id        => $subfield_data{id},
430             name      => $subfield_data{id},
431             value     => $value,
432             size      => 67,
433             maxlength => $subfield_data{maxlength},
434         };
435
436     }
437     else {
438         # it's a standard field
439         if (
440             length($value) > 100
441             or
442             ( C4::Context->preference("marcflavour") eq "UNIMARC" && $tag >= 300
443                 and $tag < 400 && $subfield eq 'a' )
444             or (    $tag >= 500
445                 and $tag < 600
446                 && C4::Context->preference("marcflavour") eq "MARC21" )
447           )
448         {
449             $subfield_data{marc_value} = {
450                 type      => 'textarea',
451                 id        => $subfield_data{id},
452                 name      => $subfield_data{id},
453                 value     => $value,
454             };
455
456         }
457         else {
458             $subfield_data{marc_value} = {
459                 type      => 'text',
460                 id        => $subfield_data{id},
461                 name      => $subfield_data{id},
462                 value     => $value,
463                 size      => 67,
464                 maxlength => $subfield_data{maxlength},
465                 readonly  => 0,
466             };
467
468         }
469     }
470     $subfield_data{'index_subfield'} = $index_subfield;
471     return \%subfield_data;
472 }
473
474
475 =head2 format_indicator
476
477 Translate indicator value for output form - specifically, map
478 indicator = ' ' to ''.  This is for the convenience of a cataloger
479 using a mouse to select an indicator input.
480
481 =cut
482
483 sub format_indicator {
484     my $ind_value = shift;
485     return '' if not defined $ind_value;
486     return '' if $ind_value eq ' ';
487     return $ind_value;
488 }
489
490 sub build_tabs {
491     my ( $template, $record, $dbh, $encoding,$input ) = @_;
492
493     # fill arrays
494     my @loop_data = ();
495     my $tag;
496
497     my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
498     my $query = "SELECT authorised_value, lib
499                 FROM authorised_values";
500     $query .= qq{ LEFT JOIN authorised_values_branches ON ( id = av_id )} if $branch_limit;
501     $query .= " WHERE category = ?";
502     $query .= " AND ( branchcode = ? OR branchcode IS NULL )" if $branch_limit;
503     $query .= " GROUP BY authorised_value,lib ORDER BY lib, lib_opac";
504     my $authorised_values_sth = $dbh->prepare( $query );
505
506     # in this array, we will push all the 10 tabs
507     # to avoid having 10 tabs in the template : they will all be in the same BIG_LOOP
508     my @BIG_LOOP;
509     my %seen;
510     my @tab_data; # all tags to display
511
512     my $max_num_tab=-1;
513     my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField( "items.itemnumber" );
514     foreach my $used ( @$usedTagsLib ){
515
516         push @tab_data,$used->{tagfield} if not $seen{$used->{tagfield}};
517         $seen{$used->{tagfield}}++;
518
519         if (   $used->{tab} > -1
520             && $used->{tab} >= $max_num_tab
521             && $used->{tagfield} ne $itemtag )
522         {
523             $max_num_tab = $used->{tab};
524         }
525     }
526     if($max_num_tab >= 9){
527         $max_num_tab = 9;
528     }
529     # loop through each tab 0 through 9
530     for ( my $tabloop = 0 ; $tabloop <= $max_num_tab ; $tabloop++ ) {
531         my @loop_data = (); #innerloop in the template.
532         my $i = 0;
533         foreach my $tag (sort @tab_data) {
534             $i++;
535             next if ! $tag;
536             my ($indicator1, $indicator2);
537             my $index_tag = CreateKey;
538
539             # if MARC::Record is not empty =>use it as master loop, then add missing subfields that should be in the tab.
540             # if MARC::Record is empty => use tab as master loop.
541             if ( $record ne -1 && ( $record->field($tag) || $tag eq '000' ) ) {
542                 my @fields;
543                 if ( $tag ne '000' ) {
544                     @fields = $record->field($tag);
545                 }
546                 else {
547                    push @fields, $record->leader(); # if tag == 000
548                 }
549                 # loop through each field
550                 foreach my $field (@fields) {
551                     
552                     my @subfields_data;
553                     if ( $tag < 10 ) {
554                         my ( $value, $subfield );
555                         if ( $tag ne '000' ) {
556                             $value    = $field->data();
557                             $subfield = "@";
558                         }
559                         else {
560                             $value    = $field;
561                             $subfield = '@';
562                         }
563                         next if ( $tagslib->{$tag}->{$subfield}->{tab} ne $tabloop );
564                         next
565                           if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq
566                             'biblio.biblionumber' );
567                         push(
568                             @subfields_data,
569                             &create_input(
570                                 $tag, $subfield, $value, $index_tag, $tabloop, $record,
571                                 $authorised_values_sth,$input
572                             )
573                         );
574                     }
575                     else {
576                         my @subfields = $field->subfields();
577                         foreach my $subfieldcount ( 0 .. $#subfields ) {
578                             my $subfield = $subfields[$subfieldcount][0];
579                             my $value    = $subfields[$subfieldcount][1];
580                             next if ( length $subfield != 1 );
581                             next if ( !defined $tagslib->{$tag}->{$subfield} || $tagslib->{$tag}->{$subfield}->{tab} ne $tabloop );
582                             push(
583                                 @subfields_data,
584                                 &create_input(
585                                     $tag, $subfield, $value, $index_tag, $tabloop,
586                                     $record, $authorised_values_sth,$input
587                                 )
588                             );
589                         }
590                     }
591
592                     # now, loop again to add parameter subfield that are not in the MARC::Record
593                     foreach my $subfield ( keys %{ $tagslib->{$tag} } )
594                     {
595                         next if ( length $subfield != 1 );
596                         next if ( $tagslib->{$tag}->{$subfield}->{tab} ne $tabloop );
597                         next if ( $tag < 10 );
598                         next
599                           if ( ( $tagslib->{$tag}->{$subfield}->{hidden} <= -4 )
600                             or ( $tagslib->{$tag}->{$subfield}->{hidden} >= 5 ) )
601                             and not ( $subfield eq "9" and
602                                       exists($tagslib->{$tag}->{'a'}->{authtypecode}) and
603                                       defined($tagslib->{$tag}->{'a'}->{authtypecode}) and
604                                       $tagslib->{$tag}->{'a'}->{authtypecode} ne "" and
605                                       $tagslib->{$tag}->{'a'}->{hidden} > -4 and
606                                       $tagslib->{$tag}->{'a'}->{hidden} < 5
607                                     )
608                           ;    #check for visibility flag
609                                # if subfield is $9 in a field whose $a is authority-controlled,
610                                # always include in the form regardless of the hidden setting - bug 2206 and 28022
611                         next if ( defined( $field->subfield($subfield) ) );
612                         push(
613                             @subfields_data,
614                             &create_input(
615                                 $tag, $subfield, '', $index_tag, $tabloop, $record,
616                                 $authorised_values_sth,$input
617                             )
618                         );
619                     }
620                     if ( $#subfields_data >= 0 ) {
621                         # build the tag entry.
622                         # note that the random() field is mandatory. Otherwise, on repeated fields, you'll 
623                         # have twice the same "name" value, and cgi->param() will return only one, making
624                         # all subfields to be merged in a single field.
625                         my %tag_data = (
626                             tag           => $tag,
627                             index         => $index_tag,
628                             tag_lib       => $tagslib->{$tag}->{lib},
629                             repeatable       => $tagslib->{$tag}->{repeatable},
630                             mandatory       => $tagslib->{$tag}->{mandatory},
631                             important       => $tagslib->{$tag}->{important},
632                             subfield_loop => \@subfields_data,
633                             fixedfield    => $tag < 10?1:0,
634                             random        => CreateKey,
635                         );
636                         if ($tag >= 10){ # no indicator for 00x tags
637                            $tag_data{indicator1} = format_indicator($field->indicator(1)),
638                            $tag_data{indicator2} = format_indicator($field->indicator(2)),
639                         }
640                         push( @loop_data, \%tag_data );
641                     }
642                  } # foreach $field end
643
644             # if breeding is empty
645             }
646             else {
647                 my @subfields_data;
648                 foreach my $subfield (
649                     sort { $a->{display_order} <=> $b->{display_order} || $a->{subfield} cmp $b->{subfield} }
650                     grep { ref($_) && %$_ } # Not a subfield (values for "important", "lib", "mandatory", etc.) or empty
651                     values %{ $tagslib->{$tag} } )
652                 {
653                     next
654                       if ( ( $subfield->{hidden} <= -4 )
655                         or ( $subfield->{hidden} >= 5 ) )
656                       and not ( $subfield->{subfield} eq "9" and
657                                 exists($tagslib->{$tag}->{'a'}->{authtypecode}) and
658                                 defined($tagslib->{$tag}->{'a'}->{authtypecode}) and
659                                 $tagslib->{$tag}->{'a'}->{authtypecode} ne "" and
660                                 $tagslib->{$tag}->{'a'}->{hidden} > -4 and
661                                 $tagslib->{$tag}->{'a'}->{hidden} < 5
662                               )
663                       ;    #check for visibility flag
664                            # if subfield is $9 in a field whose $a is authority-controlled,
665                            # always include in the form regardless of the hidden setting - bug 2206 and 28022
666                     next
667                       if ( $subfield->{tab} ne $tabloop );
668                         push(
669                         @subfields_data,
670                         &create_input(
671                             $tag, $subfield->{subfield}, '', $index_tag, $tabloop, $record,
672                             $authorised_values_sth,$input
673                         )
674                     );
675                 }
676                 if ( $#subfields_data >= 0 ) {
677                     my %tag_data = (
678                         tag              => $tag,
679                         index            => $index_tag,
680                         tag_lib          => $tagslib->{$tag}->{lib},
681                         repeatable       => $tagslib->{$tag}->{repeatable},
682                         mandatory       => $tagslib->{$tag}->{mandatory},
683                         important       => $tagslib->{$tag}->{important},
684                         indicator1       => ( $indicator1 || $tagslib->{$tag}->{ind1_defaultvalue} ), #if not set, try to load the default value
685                         indicator2       => ( $indicator2 || $tagslib->{$tag}->{ind2_defaultvalue} ), #use short-circuit operator for efficiency
686                         subfield_loop    => \@subfields_data,
687                         tagfirstsubfield => $subfields_data[0],
688                         fixedfield       => $tag < 10?1:0,
689                     );
690                     
691                     push @loop_data, \%tag_data ;
692                 }
693             }
694         }
695         if ( $#loop_data >= 0 ) {
696             push @BIG_LOOP, {
697                 number    => $tabloop,
698                 innerloop => \@loop_data,
699             };
700         }
701     }
702     $authorised_values_sth->finish;
703     $template->param( BIG_LOOP => \@BIG_LOOP );
704 }
705
706 # ========================
707 #          MAIN
708 #=========================
709 my $input = CGI->new;
710 my $error = $input->param('error');
711 my $biblionumber  = $input->param('biblionumber'); # if biblionumber exists, it's a modif, not a new biblio.
712 my $parentbiblio  = $input->param('parentbiblionumber');
713 my $breedingid    = $input->param('breedingid');
714 my $z3950         = $input->param('z3950');
715 my $op            = $input->param('op') // q{};
716 my $mode          = $input->param('mode');
717 my $frameworkcode = $input->param('frameworkcode');
718 my $redirect      = $input->param('redirect');
719 my $searchid      = $input->param('searchid') // "";
720 my $dbh           = C4::Context->dbh;
721 my $hostbiblionumber = $input->param('hostbiblionumber');
722 my $hostitemnumber = $input->param('hostitemnumber');
723 # fast cataloguing datas in transit
724 my $fa_circborrowernumber = $input->param('circborrowernumber');
725 my $fa_barcode            = $input->param('barcode');
726 my $fa_branch             = $input->param('branch');
727 my $fa_stickyduedate      = $input->param('stickyduedate');
728 my $fa_duedatespec        = $input->param('duedatespec');
729
730 my $userflags = 'edit_catalogue';
731
732 my $changed_framework = $input->param('changed_framework') // q{};
733 $frameworkcode = &GetFrameworkCode($biblionumber)
734   if ( $biblionumber and not( defined $frameworkcode) and $op ne 'addbiblio' );
735
736 if ($frameworkcode eq 'FA'){
737     $userflags = 'fast_cataloging';
738 }
739
740 $frameworkcode = '' if ( $frameworkcode eq 'Default' );
741 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
742     {
743         template_name   => "cataloguing/addbiblio.tt",
744         query           => $input,
745         type            => "intranet",
746         flagsrequired   => { editcatalogue => $userflags },
747     }
748 );
749
750 if ($biblionumber){
751     my $does_bib_exist = Koha::Biblios->find($biblionumber);
752     if (!defined $does_bib_exist){
753         $biblionumber = undef;
754         $template->param( bib_doesnt_exist => 1 );
755     }
756 }
757
758 if ($frameworkcode eq 'FA'){
759     # We need to grab and set some variables in the template for use on the additems screen
760     $template->param(
761         'circborrowernumber' => $fa_circborrowernumber,
762         'barcode'            => $fa_barcode,
763         'branch'             => $fa_branch,
764         'stickyduedate'      => $fa_stickyduedate,
765         'duedatespec'        => $fa_duedatespec,
766     );
767 } elsif ( $op ne "delete" &&
768             C4::Context->preference('EnableAdvancedCatalogingEditor') &&
769             C4::Auth::haspermission(C4::Context->userenv->{id},{'editcatalogue'=>'advanced_editor'}) &&
770             $input->cookie( 'catalogue_editor_' . $loggedinuser ) eq 'advanced' &&
771             !$breedingid ) {
772     # Only use the advanced editor for non-fast-cataloging.
773     # breedingid is not handled because those would only come off a Z39.50
774     # search initiated by the basic editor.
775     print $input->redirect( '/cgi-bin/koha/cataloguing/editor.pl' . ( $biblionumber ? ( ($op eq 'duplicate'?'#duplicate/':'#catalog/') . $biblionumber ) : '' ) );
776     exit;
777 }
778
779 my $frameworks = Koha::BiblioFrameworks->search({}, { order_by => ['frameworktext'] });
780 $template->param(
781     frameworks => $frameworks,
782     breedingid => $breedingid,
783 );
784
785 # ++ Global
786 $tagslib         = &GetMarcStructure( 1, $frameworkcode );
787 $usedTagsLib     = &GetUsedMarcStructure( $frameworkcode );
788 $mandatory_z3950 = GetMandatoryFieldZ3950($frameworkcode);
789 # -- Global
790
791 my $record   = -1;
792 my $encoding = "";
793 my (
794         $biblionumbertagfield,
795         $biblionumbertagsubfield,
796         $biblioitemnumtagfield,
797         $biblioitemnumtagsubfield,
798         $biblioitemnumber
799 );
800
801 if (($biblionumber) && !($breedingid)){
802     $record = GetMarcBiblio({ biblionumber => $biblionumber });
803 }
804 if ($breedingid) {
805     ( $record, $encoding ) = MARCfindbreeding( $breedingid ) ;
806 }
807
808 #populate hostfield if hostbiblionumber is available
809 if ($hostbiblionumber) {
810     my $marcflavour = C4::Context->preference("marcflavour");
811     $record = MARC::Record->new();
812     $record->leader('');
813     my $field =
814       PrepHostMarcField( $hostbiblionumber, $hostitemnumber, $marcflavour );
815     $record->append_fields($field);
816 }
817
818 # This is  a child record
819 if ($parentbiblio) {
820     my $marcflavour = C4::Context->preference('marcflavour');
821     $record = MARC::Record->new();
822     SetMarcUnicodeFlag($record, $marcflavour);
823     my $hostfield = prepare_host_field($parentbiblio,$marcflavour);
824     if ($hostfield) {
825         $record->append_fields($hostfield);
826     }
827 }
828
829 $is_a_modif = 0;
830
831 if ($biblionumber) {
832     $is_a_modif = 1;
833     my $title = C4::Context->preference('marcflavour') eq "UNIMARC" ? $record->subfield('200', 'a') : $record->title;
834     $template->param( title => $title );
835
836     # if it's a modif, retrieve bibli and biblioitem numbers for the future modification of old-DB.
837     ( $biblionumbertagfield, $biblionumbertagsubfield ) =
838         &GetMarcFromKohaField( "biblio.biblionumber" );
839     ( $biblioitemnumtagfield, $biblioitemnumtagsubfield ) =
840         &GetMarcFromKohaField( "biblioitems.biblioitemnumber" );
841
842     # search biblioitems value
843     my $sth =  $dbh->prepare("select biblioitemnumber from biblioitems where biblionumber=?");
844     $sth->execute($biblionumber);
845     ($biblioitemnumber) = $sth->fetchrow;
846 }
847
848 #-------------------------------------------------------------------------------------
849 if ( $op eq "addbiblio" ) {
850 #-------------------------------------------------------------------------------------
851     $template->param(
852         biblionumberdata => $biblionumber,
853     );
854     # getting html input
855     my @params = $input->multi_param();
856     $record = TransformHtmlToMarc( $input, 1 );
857     # check for a duplicate
858     my ( $duplicatebiblionumber, $duplicatetitle );
859     if ( !$is_a_modif ) {
860         ( $duplicatebiblionumber, $duplicatetitle ) = FindDuplicate($record);
861     }
862     my $confirm_not_duplicate = $input->param('confirm_not_duplicate');
863     # it is not a duplicate (determined either by Koha itself or by user checking it's not a duplicate)
864     if ( !$duplicatebiblionumber or $confirm_not_duplicate ) {
865         my $oldbibitemnum;
866         if ( $is_a_modif ) {
867             ModBiblio( $record, $biblionumber, $frameworkcode );
868         }
869         else {
870             ( $biblionumber, $oldbibitemnum ) = AddBiblio( $record, $frameworkcode );
871         }
872         if ($redirect eq "items" || ($mode ne "popup" && !$is_a_modif && $redirect ne "view" && $redirect ne "just_save")){
873             if ($frameworkcode eq 'FA'){
874                 print $input->redirect(
875             '/cgi-bin/koha/cataloguing/additem.pl?'
876             .'biblionumber='.$biblionumber
877             .'&frameworkcode='.$frameworkcode
878             .'&circborrowernumber='.$fa_circborrowernumber
879             .'&branch='.$fa_branch
880             .'&barcode='.uri_escape_utf8($fa_barcode)
881             .'&stickyduedate='.$fa_stickyduedate
882             .'&duedatespec='.$fa_duedatespec
883                 );
884                 exit;
885             }
886             else {
887                 print $input->redirect(
888                 "/cgi-bin/koha/cataloguing/additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid"
889                 );
890                 exit;
891             }
892         }
893     elsif(($is_a_modif || $redirect eq "view") && $redirect ne "just_save"){
894             my $defaultview = C4::Context->preference('IntranetBiblioDefaultView');
895             my $views = { C4::Search::enabled_staff_search_views };
896             if ($defaultview eq 'isbd' && $views->{can_view_ISBD}) {
897                 print $input->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
898             } elsif  ($defaultview eq 'marc' && $views->{can_view_MARC}) {
899                 print $input->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid");
900             } elsif  ($defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC}) {
901                 print $input->redirect("/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
902             } else {
903                 print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber&searchid=$searchid");
904             }
905             exit;
906
907     }
908     elsif ($redirect eq "just_save"){
909         my $tab = $input->param('current_tab');
910         print $input->redirect("/cgi-bin/koha/cataloguing/addbiblio.pl?biblionumber=$biblionumber&framework=$frameworkcode&tab=$tab&searchid=$searchid");
911     }
912     else {
913           $template->param(
914             biblionumber => $biblionumber,
915             done         =>1,
916             popup        =>1
917           );
918           if ( $record ne '-1' ) {
919               my $title = C4::Context->preference('marcflavour') eq "UNIMARC" ? $record->subfield('200', 'a') : $record->title;
920               $template->param( title => $title );
921           }
922           $template->param(
923             popup => $mode,
924             itemtype => $frameworkcode,
925           );
926           output_html_with_http_headers $input, $cookie, $template->output;
927           exit;     
928         }
929     } else {
930     # it may be a duplicate, warn the user and do nothing
931         build_tabs ($template, $record, $dbh,$encoding,$input);
932         $template->param(
933             biblionumber             => $biblionumber,
934             biblioitemnumber         => $biblioitemnumber,
935             duplicatebiblionumber    => $duplicatebiblionumber,
936             duplicatebibid           => $duplicatebiblionumber,
937             duplicatetitle           => $duplicatetitle,
938         );
939     }
940 }
941 elsif ( $op eq "delete" ) {
942     
943     my $error = &DelBiblio($biblionumber);
944     if ($error) {
945         warn "ERROR when DELETING BIBLIO $biblionumber : $error";
946         print "Content-Type: text/html\n\n<html><body><h1>ERROR when DELETING BIBLIO $biblionumber : $error</h1></body></html>";
947         exit;
948     }
949     
950     print $input->redirect('/cgi-bin/koha/catalogue/search.pl' . ($searchid ? "?searchid=$searchid" : ""));
951     exit;
952     
953 } else {
954    #----------------------------------------------------------------------------
955    # If we're in a duplication case, we have to set to "" the biblionumber
956    # as we'll save the biblio as a new one.
957     $template->param(
958         biblionumberdata => $biblionumber,
959         op               => $op,
960     );
961     if ( $op eq "duplicate" ) {
962         $biblionumber = "";
963     }
964
965     if($changed_framework eq "changed"){
966         $record = TransformHtmlToMarc( $input, 1 );
967     }
968     elsif( $record ne -1 ) {
969 #FIXME: it's kind of silly to go from MARC::Record to MARC::File::XML and then back again just to fix the encoding
970         eval {
971             my $uxml = $record->as_xml;
972             MARC::Record::default_record_format("UNIMARC")
973             if ( C4::Context->preference("marcflavour") eq "UNIMARC" );
974             my $urecord = MARC::Record::new_from_xml( $uxml, 'UTF-8' );
975             $record = $urecord;
976         };
977     }
978     build_tabs( $template, $record, $dbh, $encoding,$input );
979     $template->param(
980         biblionumber             => $biblionumber,
981         biblionumbertagfield        => $biblionumbertagfield,
982         biblionumbertagsubfield     => $biblionumbertagsubfield,
983         biblioitemnumtagfield    => $biblioitemnumtagfield,
984         biblioitemnumtagsubfield => $biblioitemnumtagsubfield,
985         biblioitemnumber         => $biblioitemnumber,
986         hostbiblionumber        => $hostbiblionumber,
987         hostitemnumber          => $hostitemnumber
988     );
989 }
990
991 if ( $record ne '-1' ) {
992     my $title = C4::Context->preference('marcflavour') eq "UNIMARC" ? $record->subfield('200', 'a') : $record->title;
993     $template->param( title => $title );
994 }
995 $template->param(
996     popup => $mode,
997     frameworkcode => $frameworkcode,
998     itemtype => $frameworkcode,
999     borrowernumber => $loggedinuser,
1000     tab => scalar $input->param('tab')
1001 );
1002 $template->{'VARS'}->{'searchid'} = $searchid;
1003
1004 output_html_with_http_headers $input, $cookie, $template->output;