Bug 16358: Do not redirect to the editor when deleting records
[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;    # XXX subfield_is_koha_internal_p
34 use C4::Branch;    # XXX subfield_is_koha_internal_p
35 use C4::ClassSource;
36 use C4::ImportBatch;
37 use C4::Charset;
38 use Koha::DateUtils;
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 $today_dt = dt_from_string;
299         my $year = $today_dt->year;
300         my $month = $today_dt->month;
301         my $day = $today_dt->day;
302         $value =~ s/<<YYYY>>/$year/g;
303         $value =~ s/<<MM>>/$month/g;
304         $value =~ s/<<DD>>/$day/g;
305         # And <<USER>> with surname (?)
306         my $username=(C4::Context->userenv?C4::Context->userenv->{'surname'}:"superlibrarian");
307         $value=~s/<<USER>>/$username/g;
308     
309     }
310     my $dbh = C4::Context->dbh;
311
312     # map '@' as "subfield" label for fixed fields
313     # to something that's allowed in a div id.
314     my $id_subfield = $subfield;
315     $id_subfield = "00" if $id_subfield eq "@";
316
317     my %subfield_data = (
318         tag        => $tag,
319         subfield   => $id_subfield,
320         marc_lib       => $tagslib->{$tag}->{$subfield}->{lib},
321         tag_mandatory  => $tagslib->{$tag}->{mandatory},
322         mandatory      => $tagslib->{$tag}->{$subfield}->{mandatory},
323         repeatable     => $tagslib->{$tag}->{$subfield}->{repeatable},
324         kohafield      => $tagslib->{$tag}->{$subfield}->{kohafield},
325         index          => $index_tag,
326         id             => "tag_".$tag."_subfield_".$id_subfield."_".$index_tag."_".$index_subfield,
327         value          => $value,
328         maxlength      => $tagslib->{$tag}->{$subfield}->{maxlength},
329         random         => CreateKey(),
330     );
331
332     if(exists $mandatory_z3950->{$tag.$subfield}){
333         $subfield_data{z3950_mandatory} = $mandatory_z3950->{$tag.$subfield};
334     }
335     # Subfield is hidden depending of hidden and mandatory flag, and is always
336     # shown if it contains anything or if its field is mandatory.
337     my $tdef = $tagslib->{$tag};
338     $subfield_data{visibility} = "display:none;"
339         if $tdef->{$subfield}->{hidden} % 2 == 1 &&
340            $value eq '' &&
341            !$tdef->{$subfield}->{mandatory} &&
342            !$tdef->{mandatory};
343     # expand all subfields of 773 if there is a host item provided in the input
344     $subfield_data{visibility} ="" if ($tag eq 773 and $cgi->param('hostitemnumber'));
345
346
347     # it's an authorised field
348     if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
349         $subfield_data{marc_value} =
350           build_authorized_values_list( $tag, $subfield, $value, $dbh,
351             $authorised_values_sth,$index_tag,$index_subfield );
352
353     # it's a subfield $9 linking to an authority record - see bug 2206
354     }
355     elsif ($subfield eq "9" and
356            exists($tagslib->{$tag}->{'a'}->{authtypecode}) and
357            defined($tagslib->{$tag}->{'a'}->{authtypecode}) and
358            $tagslib->{$tag}->{'a'}->{authtypecode} ne '') {
359
360         $subfield_data{marc_value} = {
361             type      => 'text',
362             id        => $subfield_data{id},
363             name      => $subfield_data{id},
364             value     => $value,
365             size      => 5,
366             maxlength => $subfield_data{maxlength},
367             readonly  => 1,
368         };
369
370     # it's a thesaurus / authority field
371     }
372     elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode} ) {
373         # when authorities auto-creation is allowed, do not set readonly
374         my $is_readonly = !C4::Context->preference("BiblioAddsAuthorities");
375
376         $subfield_data{marc_value} = {
377             type      => 'text',
378             id        => $subfield_data{id},
379             name      => $subfield_data{id},
380             value     => $value,
381             size      => 67,
382             maxlength => $subfield_data{maxlength},
383             readonly  => ($is_readonly) ? 1 : 0,
384             authtype  => $tagslib->{$tag}->{$subfield}->{authtypecode},
385         };
386
387     # it's a plugin field
388     } elsif ( $tagslib->{$tag}->{$subfield}->{'value_builder'} ) {
389         require Koha::FrameworkPlugin;
390         my $plugin = Koha::FrameworkPlugin->new( {
391             name => $tagslib->{$tag}->{$subfield}->{'value_builder'},
392         });
393         my $pars= { dbh => $dbh, record => $rec, tagslib => $tagslib,
394             id => $subfield_data{id}, tabloop => $tabloop };
395         $plugin->build( $pars );
396         if( !$plugin->errstr ) {
397             $subfield_data{marc_value} = {
398                 type           => 'text_complex',
399                 id             => $subfield_data{id},
400                 name           => $subfield_data{id},
401                 value          => $value,
402                 size           => 67,
403                 maxlength      => $subfield_data{maxlength},
404                 javascript     => $plugin->javascript,
405                 noclick        => $plugin->noclick,
406             };
407         } else {
408             warn $plugin->errstr;
409             # supply default input form
410             $subfield_data{marc_value} = {
411                 type      => 'text',
412                 id        => $subfield_data{id},
413                 name      => $subfield_data{id},
414                 value     => $value,
415                 size      => 67,
416                 maxlength => $subfield_data{maxlength},
417                 readonly  => 0,
418             };
419         }
420
421     # it's an hidden field
422     } elsif ( $tag eq '' ) {
423         $subfield_data{marc_value} = {
424             type      => 'hidden',
425             id        => $subfield_data{id},
426             name      => $subfield_data{id},
427             value     => $value,
428             size      => 67,
429             maxlength => $subfield_data{maxlength},
430         };
431
432     }
433     else {
434         # it's a standard field
435         if (
436             length($value) > 100
437             or
438             ( C4::Context->preference("marcflavour") eq "UNIMARC" && $tag >= 300
439                 and $tag < 400 && $subfield eq 'a' )
440             or (    $tag >= 500
441                 and $tag < 600
442                 && C4::Context->preference("marcflavour") eq "MARC21" )
443           )
444         {
445             $subfield_data{marc_value} = {
446                 type      => 'textarea',
447                 id        => $subfield_data{id},
448                 name      => $subfield_data{id},
449                 value     => $value,
450             };
451
452         }
453         else {
454             $subfield_data{marc_value} = {
455                 type      => 'text',
456                 id        => $subfield_data{id},
457                 name      => $subfield_data{id},
458                 value     => $value,
459                 size      => 67,
460                 maxlength => $subfield_data{maxlength},
461                 readonly  => 0,
462             };
463
464         }
465     }
466     $subfield_data{'index_subfield'} = $index_subfield;
467     return \%subfield_data;
468 }
469
470
471 =head2 format_indicator
472
473 Translate indicator value for output form - specifically, map
474 indicator = ' ' to ''.  This is for the convenience of a cataloger
475 using a mouse to select an indicator input.
476
477 =cut
478
479 sub format_indicator {
480     my $ind_value = shift;
481     return '' if not defined $ind_value;
482     return '' if $ind_value eq ' ';
483     return $ind_value;
484 }
485
486 sub build_tabs {
487     my ( $template, $record, $dbh, $encoding,$input ) = @_;
488
489     # fill arrays
490     my @loop_data = ();
491     my $tag;
492
493     my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
494     my $query = "SELECT authorised_value, lib
495                 FROM authorised_values";
496     $query .= qq{ LEFT JOIN authorised_values_branches ON ( id = av_id )} if $branch_limit;
497     $query .= " WHERE category = ?";
498     $query .= " AND ( branchcode = ? OR branchcode IS NULL )" if $branch_limit;
499     $query .= " GROUP BY lib ORDER BY lib, lib_opac";
500     my $authorised_values_sth = $dbh->prepare( $query );
501
502     # in this array, we will push all the 10 tabs
503     # to avoid having 10 tabs in the template : they will all be in the same BIG_LOOP
504     my @BIG_LOOP;
505     my %seen;
506     my @tab_data; # all tags to display
507     
508     foreach my $used ( @$usedTagsLib ){
509         push @tab_data,$used->{tagfield} if not $seen{$used->{tagfield}};
510         $seen{$used->{tagfield}}++;
511     }
512         
513     my $max_num_tab=-1;
514     foreach(@$usedTagsLib){
515         if($_->{tab} > -1 && $_->{tab} >= $max_num_tab && $_->{tagfield} != '995'){ # FIXME : MARC21 ?
516             $max_num_tab = $_->{tab}; 
517         }
518     }
519     if($max_num_tab >= 9){
520         $max_num_tab = 9;
521     }
522     # loop through each tab 0 through 9
523     for ( my $tabloop = 0 ; $tabloop <= $max_num_tab ; $tabloop++ ) {
524         my @loop_data = (); #innerloop in the template.
525         my $i = 0;
526         foreach my $tag (@tab_data) {
527             $i++;
528             next if ! $tag;
529             my ($indicator1, $indicator2);
530             my $index_tag = CreateKey;
531
532             # if MARC::Record is not empty =>use it as master loop, then add missing subfields that should be in the tab.
533             # if MARC::Record is empty => use tab as master loop.
534             if ( $record ne -1 && ( $record->field($tag) || $tag eq '000' ) ) {
535                 my @fields;
536                 if ( $tag ne '000' ) {
537                     @fields = $record->field($tag);
538                 }
539                 else {
540                    push @fields, $record->leader(); # if tag == 000
541                 }
542                 # loop through each field
543                 foreach my $field (@fields) {
544                     
545                     my @subfields_data;
546                     if ( $tag < 10 ) {
547                         my ( $value, $subfield );
548                         if ( $tag ne '000' ) {
549                             $value    = $field->data();
550                             $subfield = "@";
551                         }
552                         else {
553                             $value    = $field;
554                             $subfield = '@';
555                         }
556                         next if ( $tagslib->{$tag}->{$subfield}->{tab} ne $tabloop );
557                         next
558                           if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq
559                             'biblio.biblionumber' );
560                         push(
561                             @subfields_data,
562                             &create_input(
563                                 $tag, $subfield, $value, $index_tag, $tabloop, $record,
564                                 $authorised_values_sth,$input
565                             )
566                         );
567                     }
568                     else {
569                         my @subfields = $field->subfields();
570                         foreach my $subfieldcount ( 0 .. $#subfields ) {
571                             my $subfield = $subfields[$subfieldcount][0];
572                             my $value    = $subfields[$subfieldcount][1];
573                             next if ( length $subfield != 1 );
574                             next if ( $tagslib->{$tag}->{$subfield}->{tab} ne $tabloop );
575                             push(
576                                 @subfields_data,
577                                 &create_input(
578                                     $tag, $subfield, $value, $index_tag, $tabloop,
579                                     $record, $authorised_values_sth,$input
580                                 )
581                             );
582                         }
583                     }
584
585                     # now, loop again to add parameter subfield that are not in the MARC::Record
586                     foreach my $subfield ( sort( keys %{ $tagslib->{$tag} } ) )
587                     {
588                         next if ( length $subfield != 1 );
589                         next if ( $tagslib->{$tag}->{$subfield}->{tab} ne $tabloop );
590                         next if ( $tag < 10 );
591                         next
592                           if ( ( $tagslib->{$tag}->{$subfield}->{hidden} <= -4 )
593                             or ( $tagslib->{$tag}->{$subfield}->{hidden} >= 5 ) )
594                             and not ( $subfield eq "9" and
595                                       exists($tagslib->{$tag}->{'a'}->{authtypecode}) and
596                                       defined($tagslib->{$tag}->{'a'}->{authtypecode}) and
597                                       $tagslib->{$tag}->{'a'}->{authtypecode} ne ""
598                                     )
599                           ;    #check for visibility flag
600                                # if subfield is $9 in a field whose $a is authority-controlled,
601                                # always include in the form regardless of the hidden setting - bug 2206
602                         next if ( defined( $field->subfield($subfield) ) );
603                         push(
604                             @subfields_data,
605                             &create_input(
606                                 $tag, $subfield, '', $index_tag, $tabloop, $record,
607                                 $authorised_values_sth,$input
608                             )
609                         );
610                     }
611                     if ( $#subfields_data >= 0 ) {
612                         # build the tag entry.
613                         # note that the random() field is mandatory. Otherwise, on repeated fields, you'll 
614                         # have twice the same "name" value, and cgi->param() will return only one, making
615                         # all subfields to be merged in a single field.
616                         my %tag_data = (
617                             tag           => $tag,
618                             index         => $index_tag,
619                             tag_lib       => $tagslib->{$tag}->{lib},
620                             repeatable       => $tagslib->{$tag}->{repeatable},
621                             mandatory       => $tagslib->{$tag}->{mandatory},
622                             subfield_loop => \@subfields_data,
623                             fixedfield    => $tag < 10?1:0,
624                             random        => CreateKey,
625                         );
626                         if ($tag >= 10){ # no indicator for 00x tags
627                            $tag_data{indicator1} = format_indicator($field->indicator(1)),
628                            $tag_data{indicator2} = format_indicator($field->indicator(2)),
629                         }
630                         push( @loop_data, \%tag_data );
631                     }
632                  } # foreach $field end
633
634             # if breeding is empty
635             }
636             else {
637                 my @subfields_data;
638                 foreach my $subfield ( sort( keys %{ $tagslib->{$tag} } ) ) {
639                     next if ( length $subfield != 1 );
640                     next
641                       if ( ( $tagslib->{$tag}->{$subfield}->{hidden} <= -4 )
642                         or ( $tagslib->{$tag}->{$subfield}->{hidden} >= 5 ) )
643                       and not ( $subfield eq "9" and
644                                 exists($tagslib->{$tag}->{'a'}->{authtypecode}) and
645                                 defined($tagslib->{$tag}->{'a'}->{authtypecode}) and
646                                 $tagslib->{$tag}->{'a'}->{authtypecode} ne ""
647                               )
648                       ;    #check for visibility flag
649                            # if subfield is $9 in a field whose $a is authority-controlled,
650                            # always include in the form regardless of the hidden setting - bug 2206
651                     next
652                       if ( $tagslib->{$tag}->{$subfield}->{tab} ne $tabloop );
653                         push(
654                         @subfields_data,
655                         &create_input(
656                             $tag, $subfield, '', $index_tag, $tabloop, $record,
657                             $authorised_values_sth,$input
658                         )
659                     );
660                 }
661                 if ( $#subfields_data >= 0 ) {
662                     my %tag_data = (
663                         tag              => $tag,
664                         index            => $index_tag,
665                         tag_lib          => $tagslib->{$tag}->{lib},
666                         repeatable       => $tagslib->{$tag}->{repeatable},
667                         mandatory       => $tagslib->{$tag}->{mandatory},
668                         indicator1       => $indicator1,
669                         indicator2       => $indicator2,
670                         subfield_loop    => \@subfields_data,
671                         tagfirstsubfield => $subfields_data[0],
672                         fixedfield       => $tag < 10?1:0,
673                     );
674                     
675                     push @loop_data, \%tag_data ;
676                 }
677             }
678         }
679         if ( $#loop_data >= 0 ) {
680             push @BIG_LOOP, {
681                 number    => $tabloop,
682                 innerloop => \@loop_data,
683             };
684         }
685     }
686     $authorised_values_sth->finish;
687     $template->param( BIG_LOOP => \@BIG_LOOP );
688 }
689
690 # ========================
691 #          MAIN
692 #=========================
693 my $input = new CGI;
694 my $error = $input->param('error');
695 my $biblionumber  = $input->param('biblionumber'); # if biblionumber exists, it's a modif, not a new biblio.
696 my $parentbiblio  = $input->param('parentbiblionumber');
697 my $breedingid    = $input->param('breedingid');
698 my $z3950         = $input->param('z3950');
699 my $op            = $input->param('op');
700 my $mode          = $input->param('mode');
701 my $frameworkcode = $input->param('frameworkcode');
702 my $redirect      = $input->param('redirect');
703 my $searchid      = $input->param('searchid');
704 my $dbh           = C4::Context->dbh;
705 my $hostbiblionumber = $input->param('hostbiblionumber');
706 my $hostitemnumber = $input->param('hostitemnumber');
707 # fast cataloguing datas in transit
708 my $fa_circborrowernumber = $input->param('circborrowernumber');
709 my $fa_barcode            = $input->param('barcode');
710 my $fa_branch             = $input->param('branch');
711 my $fa_stickyduedate      = $input->param('stickyduedate');
712 my $fa_duedatespec        = $input->param('duedatespec');
713
714 my $userflags = 'edit_catalogue';
715
716 my $changed_framework = $input->param('changed_framework');
717 $frameworkcode = &GetFrameworkCode($biblionumber)
718   if ( $biblionumber and not($frameworkcode) and $op ne 'addbiblio' );
719
720 if ($frameworkcode eq 'FA'){
721     $userflags = 'fast_cataloging';
722 }
723
724 $frameworkcode = '' if ( $frameworkcode eq 'Default' );
725 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
726     {
727         template_name   => "cataloguing/addbiblio.tt",
728         query           => $input,
729         type            => "intranet",
730         authnotrequired => 0,
731         flagsrequired   => { editcatalogue => $userflags },
732     }
733 );
734
735 if ($frameworkcode eq 'FA'){
736     # We need to grab and set some variables in the template for use on the additems screen
737     $template->param(
738         'circborrowernumber' => $fa_circborrowernumber,
739         'barcode'            => $fa_barcode,
740         'branch'             => $fa_branch,
741         'stickyduedate'      => $fa_stickyduedate,
742         'duedatespec'        => $fa_duedatespec,
743     );
744 } elsif ( $op ne "delete" && C4::Context->preference('EnableAdvancedCatalogingEditor') && $input->cookie( 'catalogue_editor_' . $loggedinuser ) eq 'advanced' && !$breedingid ) {
745     # Only use the advanced editor for non-fast-cataloging.
746     # breedingid is not handled because those would only come off a Z39.50
747     # search initiated by the basic editor.
748     print $input->redirect( '/cgi-bin/koha/cataloguing/editor.pl' . ( $biblionumber ? ( '#catalog/' . $biblionumber ) : '' ) );
749     exit;
750 }
751
752
753 # Getting the list of all frameworks
754 # get framework list
755 my $frameworks = getframeworks;
756 my @frameworkcodeloop;
757 foreach my $thisframeworkcode ( keys %$frameworks ) {
758         my %row = (
759                 value         => $thisframeworkcode,
760                 frameworktext => $frameworks->{$thisframeworkcode}->{'frameworktext'},
761         );
762         if ($frameworkcode eq $thisframeworkcode){
763                 $row{'selected'} = 1;
764                 }
765         push @frameworkcodeloop, \%row;
766
767 $template->param( frameworkcodeloop => \@frameworkcodeloop,
768         breedingid => $breedingid );
769
770 # ++ Global
771 $tagslib         = &GetMarcStructure( 1, $frameworkcode );
772 $usedTagsLib     = &GetUsedMarcStructure( $frameworkcode );
773 $mandatory_z3950 = GetMandatoryFieldZ3950($frameworkcode);
774 # -- Global
775
776 my $record   = -1;
777 my $encoding = "";
778 my (
779         $biblionumbertagfield,
780         $biblionumbertagsubfield,
781         $biblioitemnumtagfield,
782         $biblioitemnumtagsubfield,
783         $biblioitemnumber
784 );
785
786 if (($biblionumber) && !($breedingid)){
787         $record = GetMarcBiblio($biblionumber);
788 }
789 if ($breedingid) {
790     ( $record, $encoding ) = MARCfindbreeding( $breedingid ) ;
791 }
792
793 #populate hostfield if hostbiblionumber is available
794 if ($hostbiblionumber) {
795     my $marcflavour = C4::Context->preference("marcflavour");
796     $record = MARC::Record->new();
797     $record->leader('');
798     my $field =
799       PrepHostMarcField( $hostbiblionumber, $hostitemnumber, $marcflavour );
800     $record->append_fields($field);
801 }
802
803 # This is  a child record
804 if ($parentbiblio) {
805     my $marcflavour = C4::Context->preference('marcflavour');
806     $record = MARC::Record->new();
807     SetMarcUnicodeFlag($record, $marcflavour);
808     my $hostfield = prepare_host_field($parentbiblio,$marcflavour);
809     if ($hostfield) {
810         $record->append_fields($hostfield);
811     }
812 }
813
814 $is_a_modif = 0;
815     
816 if ($biblionumber) {
817     $is_a_modif = 1;
818     my $title = C4::Context->preference('marcflavour') eq "UNIMARC" ? $record->subfield('200', 'a') : $record->title;
819     $template->param( title => $title );
820
821     # if it's a modif, retrieve bibli and biblioitem numbers for the future modification of old-DB.
822     ( $biblionumbertagfield, $biblionumbertagsubfield ) =
823         &GetMarcFromKohaField( "biblio.biblionumber", $frameworkcode );
824     ( $biblioitemnumtagfield, $biblioitemnumtagsubfield ) =
825         &GetMarcFromKohaField( "biblioitems.biblioitemnumber", $frameworkcode );
826             
827     # search biblioitems value
828     my $sth =  $dbh->prepare("select biblioitemnumber from biblioitems where biblionumber=?");
829     $sth->execute($biblionumber);
830     ($biblioitemnumber) = $sth->fetchrow;
831 }
832
833 #-------------------------------------------------------------------------------------
834 if ( $op eq "addbiblio" ) {
835 #-------------------------------------------------------------------------------------
836     $template->param(
837         biblionumberdata => $biblionumber,
838     );
839     # getting html input
840     my @params = $input->multi_param();
841     $record = TransformHtmlToMarc( $input, 1 );
842     # check for a duplicate
843     my ( $duplicatebiblionumber, $duplicatetitle );
844     if ( !$is_a_modif ) {
845         ( $duplicatebiblionumber, $duplicatetitle ) = FindDuplicate($record);
846     }
847     my $confirm_not_duplicate = $input->param('confirm_not_duplicate');
848     # it is not a duplicate (determined either by Koha itself or by user checking it's not a duplicate)
849     if ( !$duplicatebiblionumber or $confirm_not_duplicate ) {
850         my $oldbibitemnum;
851         if (C4::Context->preference("BiblioAddsAuthorities")){
852             BiblioAutoLink( $record, $frameworkcode );
853         } 
854         if ( $is_a_modif ) {
855             ModBiblioframework( $biblionumber, $frameworkcode ); 
856             ModBiblio( $record, $biblionumber, $frameworkcode );
857         }
858         else {
859             ( $biblionumber, $oldbibitemnum ) = AddBiblio( $record, $frameworkcode );
860         }
861         if ($redirect eq "items" || ($mode ne "popup" && !$is_a_modif && $redirect ne "view" && $redirect ne "just_save")){
862             if ($frameworkcode eq 'FA'){
863                 print $input->redirect(
864             '/cgi-bin/koha/cataloguing/additem.pl?'
865             .'biblionumber='.$biblionumber
866             .'&frameworkcode='.$frameworkcode
867             .'&circborrowernumber='.$fa_circborrowernumber
868             .'&branch='.$fa_branch
869             .'&barcode='.uri_escape_utf8($fa_barcode)
870             .'&stickyduedate='.$fa_stickyduedate
871             .'&duedatespec='.$fa_duedatespec
872                 );
873                 exit;
874             }
875             else {
876                 print $input->redirect(
877                 "/cgi-bin/koha/cataloguing/additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid"
878                 );
879                 exit;
880             }
881         }
882     elsif(($is_a_modif || $redirect eq "view") && $redirect ne "just_save"){
883             my $defaultview = C4::Context->preference('IntranetBiblioDefaultView');
884             my $views = { C4::Search::enabled_staff_search_views };
885             if ($defaultview eq 'isbd' && $views->{can_view_ISBD}) {
886                 print $input->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
887             } elsif  ($defaultview eq 'marc' && $views->{can_view_MARC}) {
888                 print $input->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid");
889             } elsif  ($defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC}) {
890                 print $input->redirect("/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
891             } else {
892                 print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber&searchid=$searchid");
893             }
894             exit;
895
896     }
897     elsif ($redirect eq "just_save"){
898         my $tab = $input->param('current_tab');
899         print $input->redirect("/cgi-bin/koha/cataloguing/addbiblio.pl?biblionumber=$biblionumber&framework=$frameworkcode&tab=$tab&searchid=$searchid");
900     }
901     else {
902           $template->param(
903             biblionumber => $biblionumber,
904             done         =>1,
905             popup        =>1
906           );
907           if ( $record ne '-1' ) {
908               my $title = C4::Context->preference('marcflavour') eq "UNIMARC" ? $record->subfield('200', 'a') : $record->title;
909               $template->param( title => $title );
910           }
911           $template->param(
912             popup => $mode,
913             itemtype => $frameworkcode,
914           );
915           output_html_with_http_headers $input, $cookie, $template->output;
916           exit;     
917         }
918     } else {
919     # it may be a duplicate, warn the user and do nothing
920         build_tabs ($template, $record, $dbh,$encoding,$input);
921         $template->param(
922             biblionumber             => $biblionumber,
923             biblioitemnumber         => $biblioitemnumber,
924             duplicatebiblionumber    => $duplicatebiblionumber,
925             duplicatebibid           => $duplicatebiblionumber,
926             duplicatetitle           => $duplicatetitle,
927         );
928     }
929 }
930 elsif ( $op eq "delete" ) {
931     
932     my $error = &DelBiblio($biblionumber);
933     if ($error) {
934         warn "ERROR when DELETING BIBLIO $biblionumber : $error";
935         print "Content-Type: text/html\n\n<html><body><h1>ERROR when DELETING BIBLIO $biblionumber : $error</h1></body></html>";
936         exit;
937     }
938     
939     print $input->redirect('/cgi-bin/koha/catalogue/search.pl');
940     exit;
941     
942 } else {
943    #----------------------------------------------------------------------------
944    # If we're in a duplication case, we have to set to "" the biblionumber
945    # as we'll save the biblio as a new one.
946     $template->param(
947         biblionumberdata => $biblionumber,
948         op               => $op,
949     );
950     if ( $op eq "duplicate" ) {
951         $biblionumber = "";
952     }
953
954     if($changed_framework eq "changed"){
955         $record = TransformHtmlToMarc( $input, 1 );
956     }
957     elsif( $record ne -1 ) {
958 #FIXME: it's kind of silly to go from MARC::Record to MARC::File::XML and then back again just to fix the encoding
959         eval {
960             my $uxml = $record->as_xml;
961             MARC::Record::default_record_format("UNIMARC")
962             if ( C4::Context->preference("marcflavour") eq "UNIMARC" );
963             my $urecord = MARC::Record::new_from_xml( $uxml, 'UTF-8' );
964             $record = $urecord;
965         };
966     }
967     build_tabs( $template, $record, $dbh, $encoding,$input );
968     $template->param(
969         biblionumber             => $biblionumber,
970         biblionumbertagfield        => $biblionumbertagfield,
971         biblionumbertagsubfield     => $biblionumbertagsubfield,
972         biblioitemnumtagfield    => $biblioitemnumtagfield,
973         biblioitemnumtagsubfield => $biblioitemnumtagsubfield,
974         biblioitemnumber         => $biblioitemnumber,
975         hostbiblionumber        => $hostbiblionumber,
976         hostitemnumber          => $hostitemnumber
977     );
978 }
979
980 if ( $record ne '-1' ) {
981     my $title = C4::Context->preference('marcflavour') eq "UNIMARC" ? $record->subfield('200', 'a') : $record->title;
982     $template->param( title => $title );
983 }
984 $template->param(
985     popup => $mode,
986     frameworkcode => $frameworkcode,
987     itemtype => $frameworkcode,
988     borrowernumber => $loggedinuser,
989     tab => scalar $input->param('tab')
990 );
991 $template->{'VARS'}->{'searchid'} = $searchid;
992
993 output_html_with_http_headers $input, $cookie, $template->output;