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