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