Bug 34993: Pass context parameters to generate_subfield_form
[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
10 # under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
13 #
14 # Koha is distributed in the hope that it will be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with Koha; if not, see <http://www.gnu.org/licenses>.
21
22 use Modern::Perl;
23
24 use CGI;
25 use C4::Output qw( output_html_with_http_headers );
26 use C4::Auth qw( get_template_and_user haspermission );
27 use C4::Biblio qw(
28     AddBiblio
29     DelBiblio
30     GetFrameworkCode
31     GetMarcFromKohaField
32     GetMarcStructure
33     GetUsedMarcStructure
34     ModBiblio
35     prepare_host_field
36     PrepHostMarcField
37     TransformHtmlToMarc
38     ApplyMarcOverlayRules
39 );
40 use C4::Search qw( FindDuplicate enabled_staff_search_views );
41 use C4::Auth qw( get_template_and_user haspermission );
42 use C4::Context;
43 use MARC::Record;
44 use C4::ClassSource qw( GetClassSources );
45 use C4::ImportBatch qw( GetImportRecordMarc );
46 use C4::Charset qw( SetMarcUnicodeFlag );
47 use Koha::BiblioFrameworks;
48 use Koha::DateUtils qw( dt_from_string );
49
50 use Koha::Biblios;
51 use Koha::ItemTypes;
52 use Koha::Libraries;
53
54 use Koha::BiblioFrameworks;
55 use Koha::Patrons;
56 use Koha::UI::Form::Builder::Biblio;
57
58 use MARC::File::USMARC;
59 use MARC::File::XML;
60 use URI::Escape qw( uri_escape_utf8 );
61
62 if ( C4::Context->preference('marcflavour') eq 'UNIMARC' ) {
63     MARC::File::XML->default_record_format('UNIMARC');
64 }
65
66 our($tagslib,$authorised_values_sth,$is_a_modif,$usedTagsLib,$mandatory_z3950);
67
68 =head1 FUNCTIONS
69
70 =head2 MARCfindbreeding
71
72     $record = MARCfindbreeding($breedingid);
73
74 Look up the import record repository for the record with
75 record with id $breedingid.  If found, returns the decoded
76 MARC::Record; otherwise, -1 is returned (FIXME).
77 Returns as second parameter the character encoding.
78
79 =cut
80
81 sub MARCfindbreeding {
82     my ( $id ) = @_;
83     my ($marc, $encoding) = GetImportRecordMarc($id);
84     # remove the - in isbn, koha store isbn without any -
85     if ($marc) {
86         my $record = MARC::Record->new_from_usmarc($marc);
87         if(C4::Context->preference('autoControlNumber') eq 'biblionumber'){
88             my @control_num = $record->field('001');
89             $record->delete_fields(@control_num);
90         }
91         my ($isbnfield,$isbnsubfield) = GetMarcFromKohaField( 'biblioitems.isbn' );
92         if ( $record->field($isbnfield) ) {
93             foreach my $field ( $record->field($isbnfield) ) {
94                 foreach my $subfield ( $field->subfield($isbnsubfield) ) {
95                     my $newisbn = $field->subfield($isbnsubfield);
96                     $newisbn =~ s/-//g;
97                     $field->update( $isbnsubfield => $newisbn );
98                 }
99             }
100         }
101         # fix the unimarc 100 coded field (with unicode information)
102         if (C4::Context->preference('marcflavour') eq 'UNIMARC' && $record->subfield(100,'a')) {
103             my $f100a=$record->subfield(100,'a');
104             my $f100 = $record->field(100);
105             my $f100temp = $f100->as_string;
106             $record->delete_field($f100);
107             if ( length($f100temp) > 28 ) {
108                 substr( $f100temp, 26, 2, "50" );
109                 $f100->update( 'a' => $f100temp );
110                 my $f100 = MARC::Field->new( '100', '', '', 'a' => $f100temp );
111                 $record->insert_fields_ordered($f100);
112             }
113         }
114                 
115         if ( !defined(ref($record)) ) {
116             return -1;
117         }
118         else {
119             # normalize author : UNIMARC specific...
120             if (    C4::Context->preference("z3950NormalizeAuthor")
121                 and C4::Context->preference("z3950AuthorAuthFields")
122                 and C4::Context->preference("marcflavour") eq 'UNIMARC' )
123             {
124                 my ( $tag, $subfield ) = GetMarcFromKohaField( "biblio.author" );
125
126                 my $auth_fields =
127                   C4::Context->preference("z3950AuthorAuthFields");
128                 my @auth_fields = split /,/, $auth_fields;
129                 my $field;
130
131                 if ( $record->field($tag) ) {
132                     foreach my $tmpfield ( $record->field($tag)->subfields ) {
133
134                         my $subfieldcode  = shift @$tmpfield;
135                         my $subfieldvalue = shift @$tmpfield;
136                         if ($field) {
137                             $field->add_subfields(
138                                 "$subfieldcode" => $subfieldvalue )
139                               if ( $subfieldcode ne $subfield );
140                         }
141                         else {
142                             $field =
143                               MARC::Field->new( $tag, "", "",
144                                 $subfieldcode => $subfieldvalue )
145                               if ( $subfieldcode ne $subfield );
146                         }
147                     }
148                 }
149                 $record->delete_field( $record->field($tag) );
150                 foreach my $fieldtag (@auth_fields) {
151                     next unless ( $record->field($fieldtag) );
152                     my $lastname  = $record->field($fieldtag)->subfield('a');
153                     my $firstname = $record->field($fieldtag)->subfield('b');
154                     my $title     = $record->field($fieldtag)->subfield('c');
155                     my $number    = $record->field($fieldtag)->subfield('d');
156                     if ($title) {
157                         $field->add_subfields(
158                                 "$subfield" => ucfirst($title) . " "
159                               . ucfirst($firstname) . " "
160                               . $number );
161                     }
162                     else {
163                         $field->add_subfields(
164                             "$subfield" => ucfirst($firstname) . ", "
165                               . ucfirst($lastname) );
166                     }
167                 }
168                 $record->insert_fields_ordered($field);
169             }
170             return $record, $encoding;
171         }
172     }
173     return -1;
174 }
175
176 =head2 CreateKey
177
178     Create a random value to set it into the input name
179
180 =cut
181
182 sub CreateKey {
183     return int(rand(1000000));
184 }
185
186 =head2 GetMandatoryFieldZ3950
187
188     This function returns a hashref which contains all mandatory field
189     to search with z3950 server.
190
191 =cut
192
193 sub GetMandatoryFieldZ3950 {
194     my $frameworkcode = shift;
195     my @isbn   = GetMarcFromKohaField( 'biblioitems.isbn' );
196     my @title  = GetMarcFromKohaField( 'biblio.title' );
197     my @author = GetMarcFromKohaField( 'biblio.author' );
198     my @issn   = GetMarcFromKohaField( 'biblioitems.issn' );
199     my @lccn   = GetMarcFromKohaField( 'biblioitems.lccn' );
200     
201     return {
202         $isbn[0].$isbn[1]     => 'isbn',
203         $title[0].$title[1]   => 'title',
204         $author[0].$author[1] => 'author',
205         $issn[0].$issn[1]     => 'issn',
206         $lccn[0].$lccn[1]     => 'lccn',
207     };
208 }
209
210 =head2 format_indicator
211
212 Translate indicator value for output form - specifically, map
213 indicator = ' ' to ''.  This is for the convenience of a cataloger
214 using a mouse to select an indicator input.
215
216 =cut
217
218 sub format_indicator {
219     my $ind_value = shift;
220     return '' if not defined $ind_value;
221     return '' if $ind_value eq ' ';
222     return $ind_value;
223 }
224
225 sub build_tabs {
226     my ( $template, $record, $dbh, $encoding,$input ) = @_;
227
228     # fill arrays
229     my @loop_data = ();
230     my $tag;
231
232     my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
233     my $query = "SELECT authorised_value, lib
234                 FROM authorised_values";
235     $query .= qq{ LEFT JOIN authorised_values_branches ON ( id = av_id )} if $branch_limit;
236     $query .= " WHERE category = ?";
237     $query .= " AND ( branchcode = ? OR branchcode IS NULL )" if $branch_limit;
238     $query .= " GROUP BY authorised_value,lib ORDER BY lib, lib_opac";
239     my $authorised_values_sth = $dbh->prepare( $query );
240
241     # in this array, we will push all the 10 tabs
242     # to avoid having 10 tabs in the template : they will all be in the same BIG_LOOP
243     my @BIG_LOOP;
244     my %seen;
245     my @tab_data; # all tags to display
246
247     my $max_num_tab=-1;
248     my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField( "items.itemnumber" );
249     foreach my $used ( @$usedTagsLib ){
250
251         push @tab_data,$used->{tagfield} if not $seen{$used->{tagfield}};
252         $seen{$used->{tagfield}}++;
253
254         if (   $used->{tab} > -1
255             && $used->{tab} >= $max_num_tab
256             && $used->{tagfield} ne $itemtag )
257         {
258             $max_num_tab = $used->{tab};
259         }
260     }
261     if($max_num_tab >= 9){
262         $max_num_tab = 9;
263     }
264
265     my $biblio_form_builder = Koha::UI::Form::Builder::Biblio->new(
266         {
267             biblionumber => scalar $input->param('biblionumber'),
268         }
269     );
270
271     # loop through each tab 0 through 9
272     for ( my $tabloop = 0 ; $tabloop <= $max_num_tab ; $tabloop++ ) {
273         my @loop_data = (); #innerloop in the template.
274         my $i = 0;
275         foreach my $tag (sort @tab_data) {
276             $i++;
277             next if ! $tag;
278             my ($indicator1, $indicator2);
279             my $index_tag = CreateKey;
280
281             # if MARC::Record is not empty =>use it as master loop, then add missing subfields that should be in the tab.
282             # if MARC::Record is empty => use tab as master loop.
283             if ( $record ne -1 && ( $record->field($tag) || $tag eq '000' ) ) {
284                 my @fields;
285                 if ( $tag ne '000' ) {
286                     @fields = $record->field($tag);
287                 }
288                 else {
289                    push @fields, $record->leader(); # if tag == 000
290                 }
291                 # loop through each field
292                 foreach my $field (@fields) {
293                     
294                     my @subfields_data;
295                     if ( $tag < 10 ) {
296                         my ( $value, $subfield );
297                         if ( $tag ne '000' ) {
298                             $value    = $field->data();
299                             $subfield = "@";
300                         }
301                         else {
302                             $value    = $field;
303                             $subfield = '@';
304                         }
305                         next if ( $tagslib->{$tag}->{$subfield}->{tab} ne $tabloop );
306                         next
307                           if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq
308                             'biblio.biblionumber' );
309                         push(
310                             @subfields_data,
311                             $biblio_form_builder->generate_subfield_form(
312                                 {
313                                     tag => $tag,
314                                     subfield => $subfield,
315                                     value => $value,
316                                     index_tag => $index_tag,
317                                     record => $record,
318                                     hostitemnumber => scalar $input->param('hostitemnumber'),
319                                     op => scalar $input->param('op'),
320                                     changed_framework => scalar $input->param('changed_framework'),
321                                     breedingid => scalar $input->param('breedingid'),
322                                     tagslib => $tagslib,
323                                     mandatory_z3950 => $mandatory_z3950,
324                                 }
325                             )
326                         );
327                     }
328                     else {
329                         my @subfields = $field->subfields();
330                         foreach my $subfieldcount ( 0 .. $#subfields ) {
331                             my $subfield = $subfields[$subfieldcount][0];
332                             my $value    = $subfields[$subfieldcount][1];
333                             next if ( length $subfield != 1 );
334                             next if ( !defined $tagslib->{$tag}->{$subfield} || $tagslib->{$tag}->{$subfield}->{tab} ne $tabloop );
335                             push(
336                                 @subfields_data,
337                                 $biblio_form_builder->generate_subfield_form(
338                                     {
339                                         tag => $tag,
340                                         subfield => $subfield,
341                                         value => $value,
342                                         index_tag => $index_tag,
343                                         record => $record,
344                                         hostitemnumber => scalar $input->param('hostitemnumber'),
345                                         op => scalar $input->param('op'),
346                                         changed_framework => scalar $input->param('changed_framework'),
347                                         breedingid => scalar $input->param('breedingid'),
348                                         tagslib => $tagslib,
349                                         mandatory_z3950 => $mandatory_z3950,
350                                     }
351                                 )
352                             );
353                         }
354                     }
355
356                     # now, loop again to add parameter subfield that are not in the MARC::Record
357                     foreach my $subfield ( sort( keys %{ $tagslib->{$tag} } ) )
358                     {
359                         next if ( length $subfield != 1 );
360                         next if ( $tagslib->{$tag}->{$subfield}->{tab} ne $tabloop );
361                         next if ( $tag < 10 );
362                         next
363                           if ( ( $tagslib->{$tag}->{$subfield}->{hidden} <= -4 )
364                             or ( $tagslib->{$tag}->{$subfield}->{hidden} >= 5 ) )
365                             and not ( $subfield eq "9" and
366                                       exists($tagslib->{$tag}->{'a'}->{authtypecode}) and
367                                       defined($tagslib->{$tag}->{'a'}->{authtypecode}) and
368                                       $tagslib->{$tag}->{'a'}->{authtypecode} ne "" and
369                                       $tagslib->{$tag}->{'a'}->{hidden} > -4 and
370                                       $tagslib->{$tag}->{'a'}->{hidden} < 5
371                                     )
372                           ;    #check for visibility flag
373                                # if subfield is $9 in a field whose $a is authority-controlled,
374                                # always include in the form regardless of the hidden setting - bug 2206 and 28022
375                         next if ( defined( $field->subfield($subfield) ) );
376                         push(
377                             @subfields_data,
378                             $biblio_form_builder->generate_subfield_form(
379                                 {
380                                     tag => $tag,
381                                     subfield => $subfield,
382                                     value => '',
383                                     index_tag => $index_tag,
384                                     record => $record,
385                                     hostitemnumber => scalar $input->param('hostitemnumber'),
386                                     op => scalar $input->param('op'),
387                                     changed_framework => scalar $input->param('changed_framework'),
388                                     breedingid => scalar $input->param('breedingid'),
389                                     tagslib => $tagslib,
390                                     mandatory_z3950 => $mandatory_z3950,
391                                 }
392                             )
393                         );
394                     }
395                     if ( $#subfields_data >= 0 ) {
396                         # build the tag entry.
397                         # note that the random() field is mandatory. Otherwise, on repeated fields, you'll 
398                         # have twice the same "name" value, and cgi->param() will return only one, making
399                         # all subfields to be merged in a single field.
400                         my %tag_data = (
401                             tag           => $tag,
402                             index         => $index_tag,
403                             tag_lib       => $tagslib->{$tag}->{lib},
404                             repeatable       => $tagslib->{$tag}->{repeatable},
405                             mandatory       => $tagslib->{$tag}->{mandatory},
406                             important       => $tagslib->{$tag}->{important},
407                             subfield_loop => \@subfields_data,
408                             fixedfield    => $tag < 10?1:0,
409                             random        => CreateKey,
410                         );
411                         if ($tag >= 10){ # no indicator for 00x tags
412                            $tag_data{indicator1} = format_indicator($field->indicator(1)),
413                            $tag_data{indicator2} = format_indicator($field->indicator(2)),
414                         }
415                         push( @loop_data, \%tag_data );
416                     }
417                  } # foreach $field end
418
419             # if breeding is empty
420             }
421             else {
422                 my @subfields_data;
423                 foreach my $subfield (
424                     sort { $a->{display_order} <=> $b->{display_order} || $a->{subfield} cmp $b->{subfield} }
425                     grep { ref($_) && %$_ } # Not a subfield (values for "important", "lib", "mandatory", etc.) or empty
426                     values %{ $tagslib->{$tag} } )
427                 {
428                     next
429                       if ( ( $subfield->{hidden} <= -4 )
430                         or ( $subfield->{hidden} >= 5 ) )
431                       and not ( $subfield->{subfield} eq "9" and
432                                 exists($tagslib->{$tag}->{'a'}->{authtypecode}) and
433                                 defined($tagslib->{$tag}->{'a'}->{authtypecode}) and
434                                 $tagslib->{$tag}->{'a'}->{authtypecode} ne "" and
435                                 $tagslib->{$tag}->{'a'}->{hidden} > -4 and
436                                 $tagslib->{$tag}->{'a'}->{hidden} < 5
437                               )
438                       ;    #check for visibility flag
439                            # if subfield is $9 in a field whose $a is authority-controlled,
440                            # always include in the form regardless of the hidden setting - bug 2206 and 28022
441                     next
442                       if ( $subfield->{tab} ne $tabloop );
443                         push(
444                         @subfields_data,
445                         $biblio_form_builder->generate_subfield_form(
446                             {
447                                 tag => $tag,
448                                 subfield => $subfield->{subfield},
449                                 value => '',
450                                 index_tag => $index_tag,
451                                 record => $record,
452                                 hostitemnumber => scalar $input->param('hostitemnumber'),
453                                 op => scalar $input->param('op'),
454                                 changed_framework => scalar $input->param('changed_framework'),
455                                 breedingid => scalar $input->param('breedingid'),
456                                 tagslib => $tagslib,
457                                 mandatory_z3950 => $mandatory_z3950,
458                             }
459                         )
460                     );
461                 }
462                 if ( $#subfields_data >= 0 ) {
463                     my %tag_data = (
464                         tag              => $tag,
465                         index            => $index_tag,
466                         tag_lib          => $tagslib->{$tag}->{lib},
467                         repeatable       => $tagslib->{$tag}->{repeatable},
468                         mandatory       => $tagslib->{$tag}->{mandatory},
469                         important       => $tagslib->{$tag}->{important},
470                         indicator1       => ( $indicator1 || $tagslib->{$tag}->{ind1_defaultvalue} ), #if not set, try to load the default value
471                         indicator2       => ( $indicator2 || $tagslib->{$tag}->{ind2_defaultvalue} ), #use short-circuit operator for efficiency
472                         subfield_loop    => \@subfields_data,
473                         tagfirstsubfield => $subfields_data[0],
474                         fixedfield       => $tag < 10?1:0,
475                     );
476                     
477                     push @loop_data, \%tag_data ;
478                 }
479             }
480         }
481         if ( $#loop_data >= 0 ) {
482             push @BIG_LOOP, {
483                 number    => $tabloop,
484                 innerloop => \@loop_data,
485             };
486         }
487     }
488     $authorised_values_sth->finish;
489     $template->param( BIG_LOOP => \@BIG_LOOP );
490 }
491
492 # ========================
493 #          MAIN
494 #=========================
495 my $input = CGI->new;
496 my $error = $input->param('error');
497 my $biblionumber  = $input->param('biblionumber'); # if biblionumber exists, it's a modif, not a new biblio.
498 my $parentbiblio  = $input->param('parentbiblionumber');
499 my $breedingid    = $input->param('breedingid');
500 my $z3950         = $input->param('z3950');
501 my $op            = $input->param('op') // q{};
502 my $mode          = $input->param('mode') // q{};
503 my $frameworkcode = $input->param('frameworkcode');
504 my $redirect      = $input->param('redirect');
505 my $searchid      = $input->param('searchid') // "";
506 my $dbh           = C4::Context->dbh;
507 my $hostbiblionumber = $input->param('hostbiblionumber');
508 my $hostitemnumber = $input->param('hostitemnumber');
509 # fast cataloguing datas in transit
510 my $fa_circborrowernumber = $input->param('circborrowernumber');
511 my $fa_barcode            = $input->param('barcode');
512 my $fa_branch             = $input->param('branch');
513 my $fa_stickyduedate      = $input->param('stickyduedate');
514 my $fa_duedatespec        = $input->param('duedatespec');
515
516 my $userflags = 'edit_catalogue';
517
518 my $changed_framework = $input->param('changed_framework') // q{};
519 $frameworkcode = &GetFrameworkCode($biblionumber)
520   if ( $biblionumber and not( defined $frameworkcode) and $op ne 'addbiblio' );
521
522 if ($frameworkcode eq 'FA'){
523     $userflags = 'fast_cataloging';
524 }
525
526 $frameworkcode = '' if ( $frameworkcode eq 'Default' );
527 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
528     {
529         template_name   => "cataloguing/addbiblio.tt",
530         query           => $input,
531         type            => "intranet",
532         flagsrequired   => { editcatalogue => $userflags },
533     }
534 );
535
536 my $biblio;
537 if ($biblionumber){
538     $biblio = Koha::Biblios->find($biblionumber);
539     unless ( $biblio ) {
540         $biblionumber = undef;
541         $template->param( bib_doesnt_exist => 1 );
542     }
543 }
544
545 if ($frameworkcode eq 'FA'){
546     # We need to grab and set some variables in the template for use on the additems screen
547     $template->param(
548         'circborrowernumber' => $fa_circborrowernumber,
549         'barcode'            => $fa_barcode,
550         'branch'             => $fa_branch,
551         'stickyduedate'      => $fa_stickyduedate,
552         'duedatespec'        => $fa_duedatespec,
553     );
554 } elsif ( $op ne "delete" &&
555             C4::Context->preference('EnableAdvancedCatalogingEditor') &&
556             C4::Auth::haspermission(C4::Context->userenv->{id},{'editcatalogue'=>'advanced_editor'}) &&
557             $input->cookie( 'catalogue_editor_' . $loggedinuser ) eq 'advanced' &&
558             !$breedingid ) {
559     # Only use the advanced editor for non-fast-cataloging.
560     # breedingid is not handled because those would only come off a Z39.50
561     # search initiated by the basic editor.
562     print $input->redirect( '/cgi-bin/koha/cataloguing/editor.pl' . ( $biblionumber ? ( ($op eq 'duplicate'?'#duplicate/':'#catalog/') . $biblionumber ) : '' ) );
563     exit;
564 }
565
566 my $frameworks = Koha::BiblioFrameworks->search({}, { order_by => ['frameworktext'] });
567 $template->param(
568     frameworks => $frameworks,
569     breedingid => $breedingid,
570 );
571
572 # ++ Global
573 $tagslib         = &GetMarcStructure( 1, $frameworkcode );
574 $usedTagsLib     = &GetUsedMarcStructure( $frameworkcode );
575 $mandatory_z3950 = GetMandatoryFieldZ3950($frameworkcode);
576 # -- Global
577
578 my $record   = -1;
579 my $encoding = "";
580 my (
581         $biblionumbertagfield,
582         $biblionumbertagsubfield,
583         $biblioitemnumtagfield,
584         $biblioitemnumtagsubfield,
585         $biblioitemnumber
586 );
587
588 if ( $biblio && !$breedingid ) {
589     eval { $record = $biblio->metadata->record };
590     if ($@) {
591         my $exception = $@;
592         $exception->rethrow unless ( $exception->isa('Koha::Exceptions::Metadata::Invalid') );
593         $record = $biblio->metadata->record_strip_nonxml;
594         $template->param( INVALID_METADATA => $exception );
595     }
596 }
597 if ($breedingid) {
598     ( $record, $encoding ) = MARCfindbreeding( $breedingid ) ;
599 }
600 if ( $record && $op eq 'duplicate' &&
601      C4::Context->preference('autoControlNumber') eq 'biblionumber' ){
602     my @control_num = $record->field('001');
603     $record->delete_fields(@control_num);
604 }
605 #populate hostfield if hostbiblionumber is available
606 if ($hostbiblionumber) {
607     my $marcflavour = C4::Context->preference("marcflavour");
608     $record = MARC::Record->new();
609     $record->leader('');
610     my $field =
611       PrepHostMarcField( $hostbiblionumber, $hostitemnumber, $marcflavour );
612     $record->append_fields($field);
613 }
614
615 # This is  a child record
616 if ($parentbiblio) {
617     my $marcflavour = C4::Context->preference('marcflavour');
618     $record = MARC::Record->new();
619     SetMarcUnicodeFlag($record, $marcflavour);
620     my $hostfield = prepare_host_field($parentbiblio,$marcflavour);
621     if ($hostfield) {
622         $record->append_fields($hostfield);
623     }
624 }
625
626 $is_a_modif = 0;
627
628 if ($biblionumber) {
629     $is_a_modif = 1;
630     my $title = C4::Context->preference('marcflavour') eq "UNIMARC" ? $record->subfield('200', 'a') : $record->title;
631     $template->param( title => $title );
632
633     # if it's a modif, retrieve bibli and biblioitem numbers for the future modification of old-DB.
634     ( $biblionumbertagfield, $biblionumbertagsubfield ) =
635         &GetMarcFromKohaField( "biblio.biblionumber" );
636     ( $biblioitemnumtagfield, $biblioitemnumtagsubfield ) =
637         &GetMarcFromKohaField( "biblioitems.biblioitemnumber" );
638
639     # search biblioitems value
640     my $sth =  $dbh->prepare("select biblioitemnumber from biblioitems where biblionumber=?");
641     $sth->execute($biblionumber);
642     ($biblioitemnumber) = $sth->fetchrow;
643     if (C4::Context->preference('MARCOverlayRules')) {
644         my $member = Koha::Patrons->find($loggedinuser);
645         $record = ApplyMarcOverlayRules(
646             {
647                 biblionumber    => $biblionumber,
648                 record          => $record,
649                 overlay_context =>  {
650                         source       => $z3950 ? 'z3950' : 'intranet',
651                         categorycode => $member->categorycode,
652                         userid       => $member->userid
653                 }
654             }
655         );
656     }
657 }
658
659 #-------------------------------------------------------------------------------------
660 if ( $op eq "addbiblio" ) {
661 #-------------------------------------------------------------------------------------
662     $template->param(
663         biblionumberdata => $biblionumber,
664     );
665     # getting html input
666     my @params = $input->multi_param();
667     $record = TransformHtmlToMarc( $input, 1 );
668     # check for a duplicate
669     my ( $duplicatebiblionumber, $duplicatetitle );
670     if ( !$is_a_modif ) {
671         ( $duplicatebiblionumber, $duplicatetitle ) = FindDuplicate($record);
672     }
673     my $confirm_not_duplicate = $input->param('confirm_not_duplicate');
674     # it is not a duplicate (determined either by Koha itself or by user checking it's not a duplicate)
675     if ( !$duplicatebiblionumber or $confirm_not_duplicate ) {
676         my $oldbibitemnum;
677         if ( $is_a_modif ) {
678             my $member = Koha::Patrons->find($loggedinuser);
679             ModBiblio(
680                 $record,
681                 $biblionumber,
682                 $frameworkcode,
683                 {
684                     overlay_context => {
685                         source       => $z3950 ? 'z3950' : 'intranet',
686                         categorycode => $member->categorycode,
687                         userid       => $member->userid
688                     }
689                 }
690             );
691         }
692         else {
693             ( $biblionumber, $oldbibitemnum ) = AddBiblio( $record, $frameworkcode );
694         }
695         if ($redirect eq "items" || ($mode ne "popup" && !$is_a_modif && $redirect ne "view" && $redirect ne "just_save")){
696             if ($frameworkcode eq 'FA'){
697                 print $input->redirect(
698             '/cgi-bin/koha/cataloguing/additem.pl?'
699             .'biblionumber='.$biblionumber
700             .'&frameworkcode='.$frameworkcode
701             .'&circborrowernumber='.$fa_circborrowernumber
702             .'&branch='.$fa_branch
703             .'&barcode='.uri_escape_utf8($fa_barcode)
704             .'&stickyduedate='.$fa_stickyduedate
705             .'&duedatespec='.$fa_duedatespec
706                 );
707                 exit;
708             }
709             else {
710                 print $input->redirect(
711                 "/cgi-bin/koha/cataloguing/additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid"
712                 );
713                 exit;
714             }
715         }
716     elsif(($is_a_modif || $redirect eq "view") && $redirect ne "just_save"){
717             my $defaultview = C4::Context->preference('IntranetBiblioDefaultView');
718             my $views = { C4::Search::enabled_staff_search_views };
719             if ($defaultview eq 'isbd' && $views->{can_view_ISBD}) {
720                 print $input->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
721             } elsif  ($defaultview eq 'marc' && $views->{can_view_MARC}) {
722                 print $input->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid");
723             } elsif  ($defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC}) {
724                 print $input->redirect("/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
725             } else {
726                 print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber&searchid=$searchid");
727             }
728             exit;
729
730     }
731     elsif ($redirect eq "just_save"){
732         my $tab = $input->param('current_tab');
733         print $input->redirect("/cgi-bin/koha/cataloguing/addbiblio.pl?biblionumber=$biblionumber&framework=$frameworkcode&tab=$tab&searchid=$searchid");
734     }
735     else {
736           $template->param(
737             biblionumber => $biblionumber,
738             done         =>1,
739             popup        =>1
740           );
741           if ( $record ne '-1' ) {
742               my $title = C4::Context->preference('marcflavour') eq "UNIMARC" ? $record->subfield('200', 'a') : $record->title;
743               $template->param( title => $title );
744           }
745           $template->param(
746             popup => $mode,
747             itemtype => $frameworkcode,
748           );
749           output_html_with_http_headers $input, $cookie, $template->output;
750           exit;     
751         }
752     } else {
753     # it may be a duplicate, warn the user and do nothing
754         build_tabs ($template, $record, $dbh,$encoding,$input);
755         $template->param(
756             biblionumber             => $biblionumber,
757             biblioitemnumber         => $biblioitemnumber,
758             duplicatebiblionumber    => $duplicatebiblionumber,
759             duplicatebibid           => $duplicatebiblionumber,
760             duplicatetitle           => $duplicatetitle,
761         );
762     }
763 }
764 elsif ( $op eq "delete" ) {
765     
766     my $error = &DelBiblio($biblionumber);
767     if ($error) {
768         warn "ERROR when DELETING BIBLIO $biblionumber : $error";
769         print "Content-Type: text/html\n\n<html><body><h1>ERROR when DELETING BIBLIO $biblionumber : $error</h1></body></html>";
770         exit;
771     }
772     
773     print $input->redirect('/cgi-bin/koha/catalogue/search.pl' . ($searchid ? "?searchid=$searchid" : ""));
774     exit;
775     
776 } else {
777    #----------------------------------------------------------------------------
778    # If we're in a duplication case, we have to set to "" the biblionumber
779    # as we'll save the biblio as a new one.
780     $template->param(
781         biblionumberdata => $biblionumber,
782         op               => $op,
783         z3950            => $z3950
784     );
785     if ( $op eq "duplicate" ) {
786         $biblionumber = "";
787     }
788
789     if($changed_framework eq "changed"){
790         $record = TransformHtmlToMarc( $input, 1 );
791     }
792     elsif( $record ne -1 ) {
793 #FIXME: it's kind of silly to go from MARC::Record to MARC::File::XML and then back again just to fix the encoding
794         eval {
795             my $uxml = $record->as_xml;
796             MARC::Record::default_record_format("UNIMARC")
797             if ( C4::Context->preference("marcflavour") eq "UNIMARC" );
798             my $urecord = MARC::Record::new_from_xml( $uxml, 'UTF-8' );
799             $record = $urecord;
800         };
801     }
802     build_tabs( $template, $record, $dbh, $encoding,$input );
803     $template->param(
804         biblionumber             => $biblionumber,
805         biblionumbertagfield        => $biblionumbertagfield,
806         biblionumbertagsubfield     => $biblionumbertagsubfield,
807         biblioitemnumtagfield    => $biblioitemnumtagfield,
808         biblioitemnumtagsubfield => $biblioitemnumtagsubfield,
809         biblioitemnumber         => $biblioitemnumber,
810         hostbiblionumber        => $hostbiblionumber,
811         hostitemnumber          => $hostitemnumber
812     );
813 }
814
815 if ( $record ne '-1' ) {
816     my $title = C4::Context->preference('marcflavour') eq "UNIMARC" ? $record->subfield('200', 'a') : $record->title;
817     $template->param( title => $title );
818 }
819 $template->param(
820     popup => $mode,
821     frameworkcode => $frameworkcode,
822     itemtype => $frameworkcode,
823     borrowernumber => $loggedinuser,
824     tab => scalar $input->param('tab')
825 );
826 $template->{'VARS'}->{'searchid'} = $searchid;
827
828 output_html_with_http_headers $input, $cookie, $template->output;