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