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