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