Bug 34146: Do not allow multiple copies to crash server
[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                                         tagslib => $tagslib,
346                                         mandatory_z3950 => $mandatory_z3950,
347                                     }
348                                 )
349                             );
350                         }
351                     }
352
353                     # now, loop again to add parameter subfield that are not in the MARC::Record
354                     foreach my $subfield ( sort( keys %{ $tagslib->{$tag} } ) )
355                     {
356                         next if ( length $subfield != 1 );
357                         next if ( $tagslib->{$tag}->{$subfield}->{tab} ne $tabloop );
358                         next if ( $tag < 10 );
359                         next
360                           if ( ( $tagslib->{$tag}->{$subfield}->{hidden} <= -4 )
361                             or ( $tagslib->{$tag}->{$subfield}->{hidden} >= 5 ) )
362                             and not ( $subfield eq "9" and
363                                       exists($tagslib->{$tag}->{'a'}->{authtypecode}) and
364                                       defined($tagslib->{$tag}->{'a'}->{authtypecode}) and
365                                       $tagslib->{$tag}->{'a'}->{authtypecode} ne "" and
366                                       $tagslib->{$tag}->{'a'}->{hidden} > -4 and
367                                       $tagslib->{$tag}->{'a'}->{hidden} < 5
368                                     )
369                           ;    #check for visibility flag
370                                # if subfield is $9 in a field whose $a is authority-controlled,
371                                # always include in the form regardless of the hidden setting - bug 2206 and 28022
372                         next if ( defined( $field->subfield($subfield) ) );
373                         push(
374                             @subfields_data,
375                             $biblio_form_builder->generate_subfield_form(
376                                 {
377                                     tag => $tag,
378                                     subfield => $subfield,
379                                     value => '',
380                                     index_tag => $index_tag,
381                                     record => $record,
382                                     hostitemnumber => scalar $input->param('hostitemnumber'),
383                                     tagslib => $tagslib,
384                                     mandatory_z3950 => $mandatory_z3950,
385                                 }
386                             )
387                         );
388                     }
389                     if ( $#subfields_data >= 0 ) {
390                         # build the tag entry.
391                         # note that the random() field is mandatory. Otherwise, on repeated fields, you'll 
392                         # have twice the same "name" value, and cgi->param() will return only one, making
393                         # all subfields to be merged in a single field.
394                         my %tag_data = (
395                             tag           => $tag,
396                             index         => $index_tag,
397                             tag_lib       => $tagslib->{$tag}->{lib},
398                             repeatable       => $tagslib->{$tag}->{repeatable},
399                             mandatory       => $tagslib->{$tag}->{mandatory},
400                             important       => $tagslib->{$tag}->{important},
401                             subfield_loop => \@subfields_data,
402                             fixedfield    => $tag < 10?1:0,
403                             random        => CreateKey,
404                         );
405                         if ($tag >= 10){ # no indicator for 00x tags
406                            $tag_data{indicator1} = format_indicator($field->indicator(1)),
407                            $tag_data{indicator2} = format_indicator($field->indicator(2)),
408                         }
409                         push( @loop_data, \%tag_data );
410                     }
411                  } # foreach $field end
412
413             # if breeding is empty
414             }
415             else {
416                 my @subfields_data;
417                 foreach my $subfield (
418                     sort { $a->{display_order} <=> $b->{display_order} || $a->{subfield} cmp $b->{subfield} }
419                     grep { ref($_) && %$_ } # Not a subfield (values for "important", "lib", "mandatory", etc.) or empty
420                     values %{ $tagslib->{$tag} } )
421                 {
422                     next
423                       if ( ( $subfield->{hidden} <= -4 )
424                         or ( $subfield->{hidden} >= 5 ) )
425                       and not ( $subfield->{subfield} eq "9" and
426                                 exists($tagslib->{$tag}->{'a'}->{authtypecode}) and
427                                 defined($tagslib->{$tag}->{'a'}->{authtypecode}) and
428                                 $tagslib->{$tag}->{'a'}->{authtypecode} ne "" and
429                                 $tagslib->{$tag}->{'a'}->{hidden} > -4 and
430                                 $tagslib->{$tag}->{'a'}->{hidden} < 5
431                               )
432                       ;    #check for visibility flag
433                            # if subfield is $9 in a field whose $a is authority-controlled,
434                            # always include in the form regardless of the hidden setting - bug 2206 and 28022
435                     next
436                       if ( $subfield->{tab} ne $tabloop );
437                         push(
438                         @subfields_data,
439                         $biblio_form_builder->generate_subfield_form(
440                             {
441                                 tag => $tag,
442                                 subfield => $subfield->{subfield},
443                                 value => '',
444                                 index_tag => $index_tag,
445                                 record => $record,
446                                 hostitemnumber => scalar $input->param('hostitemnumber'),
447                                 tagslib => $tagslib,
448                                 mandatory_z3950 => $mandatory_z3950,
449                             }
450                         )
451                     );
452                 }
453                 if ( $#subfields_data >= 0 ) {
454                     my %tag_data = (
455                         tag              => $tag,
456                         index            => $index_tag,
457                         tag_lib          => $tagslib->{$tag}->{lib},
458                         repeatable       => $tagslib->{$tag}->{repeatable},
459                         mandatory       => $tagslib->{$tag}->{mandatory},
460                         important       => $tagslib->{$tag}->{important},
461                         indicator1       => ( $indicator1 || $tagslib->{$tag}->{ind1_defaultvalue} ), #if not set, try to load the default value
462                         indicator2       => ( $indicator2 || $tagslib->{$tag}->{ind2_defaultvalue} ), #use short-circuit operator for efficiency
463                         subfield_loop    => \@subfields_data,
464                         tagfirstsubfield => $subfields_data[0],
465                         fixedfield       => $tag < 10?1:0,
466                     );
467                     
468                     push @loop_data, \%tag_data ;
469                 }
470             }
471         }
472         if ( $#loop_data >= 0 ) {
473             push @BIG_LOOP, {
474                 number    => $tabloop,
475                 innerloop => \@loop_data,
476             };
477         }
478     }
479     $authorised_values_sth->finish;
480     $template->param( BIG_LOOP => \@BIG_LOOP );
481 }
482
483 # ========================
484 #          MAIN
485 #=========================
486 my $input = CGI->new;
487 my $error = $input->param('error');
488 my $biblionumber  = $input->param('biblionumber'); # if biblionumber exists, it's a modif, not a new biblio.
489 my $parentbiblio  = $input->param('parentbiblionumber');
490 my $breedingid    = $input->param('breedingid');
491 my $z3950         = $input->param('z3950');
492 my $op            = $input->param('op') // q{};
493 my $mode          = $input->param('mode') // q{};
494 my $frameworkcode = $input->param('frameworkcode');
495 my $redirect      = $input->param('redirect');
496 my $searchid      = $input->param('searchid') // "";
497 my $dbh           = C4::Context->dbh;
498 my $hostbiblionumber = $input->param('hostbiblionumber');
499 my $hostitemnumber = $input->param('hostitemnumber');
500 # fast cataloguing datas in transit
501 my $fa_circborrowernumber = $input->param('circborrowernumber');
502 my $fa_barcode            = $input->param('barcode');
503 my $fa_branch             = $input->param('branch');
504 my $fa_stickyduedate      = $input->param('stickyduedate');
505 my $fa_duedatespec        = $input->param('duedatespec');
506
507 my $userflags = 'edit_catalogue';
508
509 my $changed_framework = $input->param('changed_framework') // q{};
510 $frameworkcode = &GetFrameworkCode($biblionumber)
511   if ( $biblionumber and not( defined $frameworkcode) and $op ne 'addbiblio' );
512
513 if ($frameworkcode eq 'FA'){
514     $userflags = 'fast_cataloging';
515 }
516
517 $frameworkcode = '' if ( $frameworkcode eq 'Default' );
518 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
519     {
520         template_name   => "cataloguing/addbiblio.tt",
521         query           => $input,
522         type            => "intranet",
523         flagsrequired   => { editcatalogue => $userflags },
524     }
525 );
526
527 my $biblio;
528 if ($biblionumber){
529     $biblio = Koha::Biblios->find($biblionumber);
530     unless ( $biblio ) {
531         $biblionumber = undef;
532         $template->param( bib_doesnt_exist => 1 );
533     }
534 }
535
536 if ($frameworkcode eq 'FA'){
537     # We need to grab and set some variables in the template for use on the additems screen
538     $template->param(
539         'circborrowernumber' => $fa_circborrowernumber,
540         'barcode'            => $fa_barcode,
541         'branch'             => $fa_branch,
542         'stickyduedate'      => $fa_stickyduedate,
543         'duedatespec'        => $fa_duedatespec,
544     );
545 } elsif ( $op ne "delete" &&
546             C4::Context->preference('EnableAdvancedCatalogingEditor') &&
547             C4::Auth::haspermission(C4::Context->userenv->{id},{'editcatalogue'=>'advanced_editor'}) &&
548             $input->cookie( 'catalogue_editor_' . $loggedinuser ) eq 'advanced' &&
549             !$breedingid ) {
550     # Only use the advanced editor for non-fast-cataloging.
551     # breedingid is not handled because those would only come off a Z39.50
552     # search initiated by the basic editor.
553     print $input->redirect( '/cgi-bin/koha/cataloguing/editor.pl' . ( $biblionumber ? ( ($op eq 'duplicate'?'#duplicate/':'#catalog/') . $biblionumber ) : '' ) );
554     exit;
555 }
556
557 my $frameworks = Koha::BiblioFrameworks->search({}, { order_by => ['frameworktext'] });
558 $template->param(
559     frameworks => $frameworks,
560     breedingid => $breedingid,
561 );
562
563 # ++ Global
564 $tagslib         = &GetMarcStructure( 1, $frameworkcode );
565 $usedTagsLib     = &GetUsedMarcStructure( $frameworkcode );
566 $mandatory_z3950 = GetMandatoryFieldZ3950($frameworkcode);
567 # -- Global
568
569 my $record   = -1;
570 my $encoding = "";
571 my (
572         $biblionumbertagfield,
573         $biblionumbertagsubfield,
574         $biblioitemnumtagfield,
575         $biblioitemnumtagsubfield,
576         $biblioitemnumber
577 );
578
579 if ( $biblio && !$breedingid ) {
580     $record = $biblio->metadata->record;
581 }
582 if ($breedingid) {
583     ( $record, $encoding ) = MARCfindbreeding( $breedingid ) ;
584 }
585 if ( $record && $op eq 'duplicate' &&
586      C4::Context->preference('autoControlNumber') eq 'biblionumber' ){
587     my @control_num = $record->field('001');
588     $record->delete_fields(@control_num);
589 }
590 #populate hostfield if hostbiblionumber is available
591 if ($hostbiblionumber) {
592     my $marcflavour = C4::Context->preference("marcflavour");
593     $record = MARC::Record->new();
594     $record->leader('');
595     my $field =
596       PrepHostMarcField( $hostbiblionumber, $hostitemnumber, $marcflavour );
597     $record->append_fields($field);
598 }
599
600 # This is  a child record
601 if ($parentbiblio) {
602     my $marcflavour = C4::Context->preference('marcflavour');
603     $record = MARC::Record->new();
604     SetMarcUnicodeFlag($record, $marcflavour);
605     my $hostfield = prepare_host_field($parentbiblio,$marcflavour);
606     if ($hostfield) {
607         $record->append_fields($hostfield);
608     }
609 }
610
611 $is_a_modif = 0;
612
613 if ($biblionumber) {
614     $is_a_modif = 1;
615     my $title = C4::Context->preference('marcflavour') eq "UNIMARC" ? $record->subfield('200', 'a') : $record->title;
616     $template->param( title => $title );
617
618     # if it's a modif, retrieve bibli and biblioitem numbers for the future modification of old-DB.
619     ( $biblionumbertagfield, $biblionumbertagsubfield ) =
620         &GetMarcFromKohaField( "biblio.biblionumber" );
621     ( $biblioitemnumtagfield, $biblioitemnumtagsubfield ) =
622         &GetMarcFromKohaField( "biblioitems.biblioitemnumber" );
623
624     # search biblioitems value
625     my $sth =  $dbh->prepare("select biblioitemnumber from biblioitems where biblionumber=?");
626     $sth->execute($biblionumber);
627     ($biblioitemnumber) = $sth->fetchrow;
628     if (C4::Context->preference('MARCOverlayRules')) {
629         my $member = Koha::Patrons->find($loggedinuser);
630         $record = ApplyMarcOverlayRules(
631             {
632                 biblionumber    => $biblionumber,
633                 record          => $record,
634                 overlay_context =>  {
635                         source       => $z3950 ? 'z3950' : 'intranet',
636                         categorycode => $member->categorycode,
637                         userid       => $member->userid
638                 }
639             }
640         );
641     }
642 }
643
644 #-------------------------------------------------------------------------------------
645 if ( $op eq "addbiblio" ) {
646 #-------------------------------------------------------------------------------------
647     $template->param(
648         biblionumberdata => $biblionumber,
649     );
650     # getting html input
651     my @params = $input->multi_param();
652     $record = TransformHtmlToMarc( $input, 1 );
653     # check for a duplicate
654     my ( $duplicatebiblionumber, $duplicatetitle );
655     if ( !$is_a_modif ) {
656         ( $duplicatebiblionumber, $duplicatetitle ) = FindDuplicate($record);
657     }
658     my $confirm_not_duplicate = $input->param('confirm_not_duplicate');
659     # it is not a duplicate (determined either by Koha itself or by user checking it's not a duplicate)
660     if ( !$duplicatebiblionumber or $confirm_not_duplicate ) {
661         my $oldbibitemnum;
662         if ( $is_a_modif ) {
663             my $member = Koha::Patrons->find($loggedinuser);
664             ModBiblio(
665                 $record,
666                 $biblionumber,
667                 $frameworkcode,
668                 {
669                     overlay_context => {
670                         source       => $z3950 ? 'z3950' : 'intranet',
671                         categorycode => $member->categorycode,
672                         userid       => $member->userid
673                     }
674                 }
675             );
676         }
677         else {
678             ( $biblionumber, $oldbibitemnum ) = AddBiblio( $record, $frameworkcode );
679         }
680         if ($redirect eq "items" || ($mode ne "popup" && !$is_a_modif && $redirect ne "view" && $redirect ne "just_save")){
681             if ($frameworkcode eq 'FA'){
682                 print $input->redirect(
683             '/cgi-bin/koha/cataloguing/additem.pl?'
684             .'biblionumber='.$biblionumber
685             .'&frameworkcode='.$frameworkcode
686             .'&circborrowernumber='.$fa_circborrowernumber
687             .'&branch='.$fa_branch
688             .'&barcode='.uri_escape_utf8($fa_barcode)
689             .'&stickyduedate='.$fa_stickyduedate
690             .'&duedatespec='.$fa_duedatespec
691                 );
692                 exit;
693             }
694             else {
695                 print $input->redirect(
696                 "/cgi-bin/koha/cataloguing/additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid"
697                 );
698                 exit;
699             }
700         }
701     elsif(($is_a_modif || $redirect eq "view") && $redirect ne "just_save"){
702             my $defaultview = C4::Context->preference('IntranetBiblioDefaultView');
703             my $views = { C4::Search::enabled_staff_search_views };
704             if ($defaultview eq 'isbd' && $views->{can_view_ISBD}) {
705                 print $input->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
706             } elsif  ($defaultview eq 'marc' && $views->{can_view_MARC}) {
707                 print $input->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid");
708             } elsif  ($defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC}) {
709                 print $input->redirect("/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
710             } else {
711                 print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber&searchid=$searchid");
712             }
713             exit;
714
715     }
716     elsif ($redirect eq "just_save"){
717         my $tab = $input->param('current_tab');
718         print $input->redirect("/cgi-bin/koha/cataloguing/addbiblio.pl?biblionumber=$biblionumber&framework=$frameworkcode&tab=$tab&searchid=$searchid");
719     }
720     else {
721           $template->param(
722             biblionumber => $biblionumber,
723             done         =>1,
724             popup        =>1
725           );
726           if ( $record ne '-1' ) {
727               my $title = C4::Context->preference('marcflavour') eq "UNIMARC" ? $record->subfield('200', 'a') : $record->title;
728               $template->param( title => $title );
729           }
730           $template->param(
731             popup => $mode,
732             itemtype => $frameworkcode,
733           );
734           output_html_with_http_headers $input, $cookie, $template->output;
735           exit;     
736         }
737     } else {
738     # it may be a duplicate, warn the user and do nothing
739         build_tabs ($template, $record, $dbh,$encoding,$input);
740         $template->param(
741             biblionumber             => $biblionumber,
742             biblioitemnumber         => $biblioitemnumber,
743             duplicatebiblionumber    => $duplicatebiblionumber,
744             duplicatebibid           => $duplicatebiblionumber,
745             duplicatetitle           => $duplicatetitle,
746         );
747     }
748 }
749 elsif ( $op eq "delete" ) {
750     
751     my $error = &DelBiblio($biblionumber);
752     if ($error) {
753         warn "ERROR when DELETING BIBLIO $biblionumber : $error";
754         print "Content-Type: text/html\n\n<html><body><h1>ERROR when DELETING BIBLIO $biblionumber : $error</h1></body></html>";
755         exit;
756     }
757     
758     print $input->redirect('/cgi-bin/koha/catalogue/search.pl' . ($searchid ? "?searchid=$searchid" : ""));
759     exit;
760     
761 } else {
762    #----------------------------------------------------------------------------
763    # If we're in a duplication case, we have to set to "" the biblionumber
764    # as we'll save the biblio as a new one.
765     $template->param(
766         biblionumberdata => $biblionumber,
767         op               => $op,
768         z3950            => $z3950
769     );
770     if ( $op eq "duplicate" ) {
771         $biblionumber = "";
772     }
773
774     if($changed_framework eq "changed"){
775         $record = TransformHtmlToMarc( $input, 1 );
776     }
777     elsif( $record ne -1 ) {
778 #FIXME: it's kind of silly to go from MARC::Record to MARC::File::XML and then back again just to fix the encoding
779         eval {
780             my $uxml = $record->as_xml;
781             MARC::Record::default_record_format("UNIMARC")
782             if ( C4::Context->preference("marcflavour") eq "UNIMARC" );
783             my $urecord = MARC::Record::new_from_xml( $uxml, 'UTF-8' );
784             $record = $urecord;
785         };
786     }
787     build_tabs( $template, $record, $dbh, $encoding,$input );
788     $template->param(
789         biblionumber             => $biblionumber,
790         biblionumbertagfield        => $biblionumbertagfield,
791         biblionumbertagsubfield     => $biblionumbertagsubfield,
792         biblioitemnumtagfield    => $biblioitemnumtagfield,
793         biblioitemnumtagsubfield => $biblioitemnumtagsubfield,
794         biblioitemnumber         => $biblioitemnumber,
795         hostbiblionumber        => $hostbiblionumber,
796         hostitemnumber          => $hostitemnumber
797     );
798 }
799
800 if ( $record ne '-1' ) {
801     my $title = C4::Context->preference('marcflavour') eq "UNIMARC" ? $record->subfield('200', 'a') : $record->title;
802     $template->param( title => $title );
803 }
804 $template->param(
805     popup => $mode,
806     frameworkcode => $frameworkcode,
807     itemtype => $frameworkcode,
808     borrowernumber => $loggedinuser,
809     tab => scalar $input->param('tab')
810 );
811 $template->{'VARS'}->{'searchid'} = $searchid;
812
813 output_html_with_http_headers $input, $cookie, $template->output;