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