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