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