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