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