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