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