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