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