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