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