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