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