Bug 15407: Koha::Patron::Categories - replace C4::Category->all
[koha.git] / cataloguing / addbiblio.pl
1 #!/usr/bin/perl 
2
3
4 # Copyright 2000-2002 Katipo Communications
5 # Copyright 2004-2010 BibLibre
6 #
7 # This file is part of Koha.
8 #
9 # Koha is free software; you can redistribute it and/or modify it
10 # under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
13 #
14 # Koha is distributed in the hope that it will be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with Koha; if not, see <http://www.gnu.org/licenses>.
21
22 use strict;
23 #use warnings; FIXME - Bug 2505
24 use CGI q(-utf8);
25 use C4::Output;
26 use C4::Auth;
27 use C4::Biblio;
28 use C4::Search;
29 use C4::AuthoritiesMarc;
30 use C4::Context;
31 use MARC::Record;
32 use C4::Log;
33 use C4::Koha;
34 use C4::Branch;
35 use C4::ClassSource;
36 use C4::ImportBatch;
37 use C4::Charset;
38 use Koha::BiblioFrameworks;
39 use Koha::DateUtils;
40
41 use Date::Calc qw(Today);
42 use MARC::File::USMARC;
43 use MARC::File::XML;
44 use URI::Escape;
45
46 if ( C4::Context->preference('marcflavour') eq 'UNIMARC' ) {
47     MARC::File::XML->default_record_format('UNIMARC');
48 }
49
50 our($tagslib,$authorised_values_sth,$is_a_modif,$usedTagsLib,$mandatory_z3950);
51
52 =head1 FUNCTIONS
53
54 =head2 MARCfindbreeding
55
56     $record = MARCfindbreeding($breedingid);
57
58 Look up the import record repository for the record with
59 record with id $breedingid.  If found, returns the decoded
60 MARC::Record; otherwise, -1 is returned (FIXME).
61 Returns as second parameter the character encoding.
62
63 =cut
64
65 sub MARCfindbreeding {
66     my ( $id ) = @_;
67     my ($marc, $encoding) = GetImportRecordMarc($id);
68     # remove the - in isbn, koha store isbn without any -
69     if ($marc) {
70         my $record = MARC::Record->new_from_usmarc($marc);
71         my ($isbnfield,$isbnsubfield) = GetMarcFromKohaField('biblioitems.isbn','');
72         if ( $record->field($isbnfield) ) {
73             foreach my $field ( $record->field($isbnfield) ) {
74                 foreach my $subfield ( $field->subfield($isbnsubfield) ) {
75                     my $newisbn = $field->subfield($isbnsubfield);
76                     $newisbn =~ s/-//g;
77                     $field->update( $isbnsubfield => $newisbn );
78                 }
79             }
80         }
81         # fix the unimarc 100 coded field (with unicode information)
82         if (C4::Context->preference('marcflavour') eq 'UNIMARC' && $record->subfield(100,'a')) {
83             my $f100a=$record->subfield(100,'a');
84             my $f100 = $record->field(100);
85             my $f100temp = $f100->as_string;
86             $record->delete_field($f100);
87             if ( length($f100temp) > 28 ) {
88                 substr( $f100temp, 26, 2, "50" );
89                 $f100->update( 'a' => $f100temp );
90                 my $f100 = MARC::Field->new( '100', '', '', 'a' => $f100temp );
91                 $record->insert_fields_ordered($f100);
92             }
93         }
94                 
95         if ( !defined(ref($record)) ) {
96             return -1;
97         }
98         else {
99             # normalize author : UNIMARC specific...
100             if (    C4::Context->preference("z3950NormalizeAuthor")
101                 and C4::Context->preference("z3950AuthorAuthFields")
102                 and C4::Context->preference("marcflavour") eq 'UNIMARC' )
103             {
104                 my ( $tag, $subfield ) = GetMarcFromKohaField("biblio.author", '');
105
106  #                 my $summary = C4::Context->preference("z3950authortemplate");
107                 my $auth_fields =
108                   C4::Context->preference("z3950AuthorAuthFields");
109                 my @auth_fields = split /,/, $auth_fields;
110                 my $field;
111
112                 if ( $record->field($tag) ) {
113                     foreach my $tmpfield ( $record->field($tag)->subfields ) {
114
115        #                        foreach my $subfieldcode ($tmpfield->subfields){
116                         my $subfieldcode  = shift @$tmpfield;
117                         my $subfieldvalue = shift @$tmpfield;
118                         if ($field) {
119                             $field->add_subfields(
120                                 "$subfieldcode" => $subfieldvalue )
121                               if ( $subfieldcode ne $subfield );
122                         }
123                         else {
124                             $field =
125                               MARC::Field->new( $tag, "", "",
126                                 $subfieldcode => $subfieldvalue )
127                               if ( $subfieldcode ne $subfield );
128                         }
129                     }
130                 }
131                 $record->delete_field( $record->field($tag) );
132                 foreach my $fieldtag (@auth_fields) {
133                     next unless ( $record->field($fieldtag) );
134                     my $lastname  = $record->field($fieldtag)->subfield('a');
135                     my $firstname = $record->field($fieldtag)->subfield('b');
136                     my $title     = $record->field($fieldtag)->subfield('c');
137                     my $number    = $record->field($fieldtag)->subfield('d');
138                     if ($title) {
139
140 #                         $field->add_subfields("$subfield"=>"[ ".ucfirst($title).ucfirst($firstname)." ".$number." ]");
141                         $field->add_subfields(
142                                 "$subfield" => ucfirst($title) . " "
143                               . ucfirst($firstname) . " "
144                               . $number );
145                     }
146                     else {
147
148 #                       $field->add_subfields("$subfield"=>"[ ".ucfirst($firstname).", ".ucfirst($lastname)." ]");
149                         $field->add_subfields(
150                             "$subfield" => ucfirst($firstname) . ", "
151                               . ucfirst($lastname) );
152                     }
153                 }
154                 $record->insert_fields_ordered($field);
155             }
156             return $record, $encoding;
157         }
158     }
159     return -1;
160 }
161
162 =head2 build_authorized_values_list
163
164 =cut
165
166 sub build_authorized_values_list {
167     my ( $tag, $subfield, $value, $dbh, $authorised_values_sth,$index_tag,$index_subfield ) = @_;
168
169     my @authorised_values;
170     my %authorised_lib;
171
172     # builds list, depending on authorised value...
173
174     #---- branch
175     if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
176         #Use GetBranches($onlymine)
177         my $onlymine =
178              C4::Context->preference('IndependentBranches')
179           && C4::Context->userenv
180           && !C4::Context->IsSuperLibrarian()
181           && C4::Context->userenv->{branch};
182         my $branches = GetBranches($onlymine);
183         foreach my $thisbranch ( sort keys %$branches ) {
184             push @authorised_values, $thisbranch;
185             $authorised_lib{$thisbranch} = $branches->{$thisbranch}->{'branchname'};
186         }
187
188     }
189     elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
190         push @authorised_values, ""
191           unless ( $tagslib->{$tag}->{$subfield}->{mandatory}
192             && ( $value || $tagslib->{$tag}->{$subfield}->{defaultvalue} ) );
193
194         my $itemtype;
195         my $itemtypes = GetItemTypes( style => 'array' );
196         for my $itemtype ( @$itemtypes ) {
197             push @authorised_values, $itemtype->{itemtype};
198             $authorised_lib{$itemtype->{itemtype}} = $itemtype->{translated_description};
199         }
200         $value = $itemtype unless ($value);
201     }
202     elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
203         push @authorised_values, ""
204           unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
205
206         my $class_sources = GetClassSources();
207
208         my $default_source = C4::Context->preference("DefaultClassificationSource");
209
210         foreach my $class_source (sort keys %$class_sources) {
211             next unless $class_sources->{$class_source}->{'used'} or
212                         ($value and $class_source eq $value) or
213                         ($class_source eq $default_source);
214             push @authorised_values, $class_source;
215             $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
216         }
217         $value = $default_source unless $value;
218     }
219     else {
220         my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
221         $authorised_values_sth->execute(
222             $tagslib->{$tag}->{$subfield}->{authorised_value},
223             $branch_limit ? $branch_limit : (),
224         );
225
226         push @authorised_values, ""
227           unless ( $tagslib->{$tag}->{$subfield}->{mandatory}
228             && ( $value || $tagslib->{$tag}->{$subfield}->{defaultvalue} ) );
229
230         while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
231             push @authorised_values, $value;
232             $authorised_lib{$value} = $lib;
233         }
234     }
235     $authorised_values_sth->finish;
236     return {
237         type     => 'select',
238         id       => "tag_".$tag."_subfield_".$subfield."_".$index_tag."_".$index_subfield,
239         name     => "tag_".$tag."_subfield_".$subfield."_".$index_tag."_".$index_subfield,
240         default  => $value,
241         values   => \@authorised_values,
242         labels   => \%authorised_lib,
243     };
244
245 }
246
247 =head2 CreateKey
248
249     Create a random value to set it into the input name
250
251 =cut
252
253 sub CreateKey {
254     return int(rand(1000000));
255 }
256
257 =head2 GetMandatoryFieldZ3950
258
259     This function return an hashref which containts all mandatory field
260     to search with z3950 server.
261
262 =cut
263
264 sub GetMandatoryFieldZ3950 {
265     my $frameworkcode = shift;
266     my @isbn   = GetMarcFromKohaField('biblioitems.isbn',$frameworkcode);
267     my @title  = GetMarcFromKohaField('biblio.title',$frameworkcode);
268     my @author = GetMarcFromKohaField('biblio.author',$frameworkcode);
269     my @issn   = GetMarcFromKohaField('biblioitems.issn',$frameworkcode);
270     my @lccn   = GetMarcFromKohaField('biblioitems.lccn',$frameworkcode);
271     
272     return {
273         $isbn[0].$isbn[1]     => 'isbn',
274         $title[0].$title[1]   => 'title',
275         $author[0].$author[1] => 'author',
276         $issn[0].$issn[1]     => 'issn',
277         $lccn[0].$lccn[1]     => 'lccn',
278     };
279 }
280
281 =head2 create_input
282
283  builds the <input ...> entry for a subfield.
284
285 =cut
286
287 sub create_input {
288     my ( $tag, $subfield, $value, $index_tag, $tabloop, $rec, $authorised_values_sth,$cgi ) = @_;
289     
290     my $index_subfield = CreateKey(); # create a specifique key for each subfield
291
292     $value =~ s/"/&quot;/g;
293
294     # if there is no value provided but a default value in parameters, get it
295     if ( $value eq '' ) {
296         $value = $tagslib->{$tag}->{$subfield}->{defaultvalue};
297
298         # get today date & replace <<YYYY>>, <<MM>>, <<DD>> if provided in the default value
299         my $today_dt = dt_from_string;
300         my $year = $today_dt->year;
301         my $month = $today_dt->month;
302         my $day = $today_dt->day;
303         $value =~ s/<<YYYY>>/$year/g;
304         $value =~ s/<<MM>>/$month/g;
305         $value =~ s/<<DD>>/$day/g;
306         # And <<USER>> with surname (?)
307         my $username=(C4::Context->userenv?C4::Context->userenv->{'surname'}:"superlibrarian");
308         $value=~s/<<USER>>/$username/g;
309     
310     }
311     my $dbh = C4::Context->dbh;
312
313     # map '@' as "subfield" label for fixed fields
314     # to something that's allowed in a div id.
315     my $id_subfield = $subfield;
316     $id_subfield = "00" if $id_subfield eq "@";
317
318     my %subfield_data = (
319         tag        => $tag,
320         subfield   => $id_subfield,
321         marc_lib       => $tagslib->{$tag}->{$subfield}->{lib},
322         tag_mandatory  => $tagslib->{$tag}->{mandatory},
323         mandatory      => $tagslib->{$tag}->{$subfield}->{mandatory},
324         repeatable     => $tagslib->{$tag}->{$subfield}->{repeatable},
325         kohafield      => $tagslib->{$tag}->{$subfield}->{kohafield},
326         index          => $index_tag,
327         id             => "tag_".$tag."_subfield_".$id_subfield."_".$index_tag."_".$index_subfield,
328         value          => $value,
329         maxlength      => $tagslib->{$tag}->{$subfield}->{maxlength},
330         random         => CreateKey(),
331     );
332
333     if(exists $mandatory_z3950->{$tag.$subfield}){
334         $subfield_data{z3950_mandatory} = $mandatory_z3950->{$tag.$subfield};
335     }
336     # Subfield is hidden depending of hidden and mandatory flag, and is always
337     # shown if it contains anything or if its field is mandatory.
338     my $tdef = $tagslib->{$tag};
339     $subfield_data{visibility} = "display:none;"
340         if $tdef->{$subfield}->{hidden} % 2 == 1 &&
341            $value eq '' &&
342            !$tdef->{$subfield}->{mandatory} &&
343            !$tdef->{mandatory};
344     # expand all subfields of 773 if there is a host item provided in the input
345     $subfield_data{visibility} ="" if ($tag eq 773 and $cgi->param('hostitemnumber'));
346
347
348     # it's an authorised field
349     if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
350         $subfield_data{marc_value} =
351           build_authorized_values_list( $tag, $subfield, $value, $dbh,
352             $authorised_values_sth,$index_tag,$index_subfield );
353
354     # it's a subfield $9 linking to an authority record - see bug 2206
355     }
356     elsif ($subfield eq "9" and
357            exists($tagslib->{$tag}->{'a'}->{authtypecode}) and
358            defined($tagslib->{$tag}->{'a'}->{authtypecode}) and
359            $tagslib->{$tag}->{'a'}->{authtypecode} ne '') {
360
361         $subfield_data{marc_value} = {
362             type      => 'text',
363             id        => $subfield_data{id},
364             name      => $subfield_data{id},
365             value     => $value,
366             size      => 5,
367             maxlength => $subfield_data{maxlength},
368             readonly  => 1,
369         };
370
371     # it's a thesaurus / authority field
372     }
373     elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode} ) {
374         # when authorities auto-creation is allowed, do not set readonly
375         my $is_readonly = !C4::Context->preference("BiblioAddsAuthorities");
376
377         $subfield_data{marc_value} = {
378             type      => 'text',
379             id        => $subfield_data{id},
380             name      => $subfield_data{id},
381             value     => $value,
382             size      => 67,
383             maxlength => $subfield_data{maxlength},
384             readonly  => ($is_readonly) ? 1 : 0,
385             authtype  => $tagslib->{$tag}->{$subfield}->{authtypecode},
386         };
387
388     # it's a plugin field
389     } elsif ( $tagslib->{$tag}->{$subfield}->{'value_builder'} ) {
390         require Koha::FrameworkPlugin;
391         my $plugin = Koha::FrameworkPlugin->new( {
392             name => $tagslib->{$tag}->{$subfield}->{'value_builder'},
393         });
394         my $pars= { dbh => $dbh, record => $rec, tagslib => $tagslib,
395             id => $subfield_data{id}, tabloop => $tabloop };
396         $plugin->build( $pars );
397         if( !$plugin->errstr ) {
398             $subfield_data{marc_value} = {
399                 type           => 'text_complex',
400                 id             => $subfield_data{id},
401                 name           => $subfield_data{id},
402                 value          => $value,
403                 size           => 67,
404                 maxlength      => $subfield_data{maxlength},
405                 javascript     => $plugin->javascript,
406                 noclick        => $plugin->noclick,
407             };
408         } else {
409             warn $plugin->errstr;
410             # supply default input form
411             $subfield_data{marc_value} = {
412                 type      => 'text',
413                 id        => $subfield_data{id},
414                 name      => $subfield_data{id},
415                 value     => $value,
416                 size      => 67,
417                 maxlength => $subfield_data{maxlength},
418                 readonly  => 0,
419             };
420         }
421
422     # it's an hidden field
423     } elsif ( $tag eq '' ) {
424         $subfield_data{marc_value} = {
425             type      => 'hidden',
426             id        => $subfield_data{id},
427             name      => $subfield_data{id},
428             value     => $value,
429             size      => 67,
430             maxlength => $subfield_data{maxlength},
431         };
432
433     }
434     else {
435         # it's a standard field
436         if (
437             length($value) > 100
438             or
439             ( C4::Context->preference("marcflavour") eq "UNIMARC" && $tag >= 300
440                 and $tag < 400 && $subfield eq 'a' )
441             or (    $tag >= 500
442                 and $tag < 600
443                 && C4::Context->preference("marcflavour") eq "MARC21" )
444           )
445         {
446             $subfield_data{marc_value} = {
447                 type      => 'textarea',
448                 id        => $subfield_data{id},
449                 name      => $subfield_data{id},
450                 value     => $value,
451             };
452
453         }
454         else {
455             $subfield_data{marc_value} = {
456                 type      => 'text',
457                 id        => $subfield_data{id},
458                 name      => $subfield_data{id},
459                 value     => $value,
460                 size      => 67,
461                 maxlength => $subfield_data{maxlength},
462                 readonly  => 0,
463             };
464
465         }
466     }
467     $subfield_data{'index_subfield'} = $index_subfield;
468     return \%subfield_data;
469 }
470
471
472 =head2 format_indicator
473
474 Translate indicator value for output form - specifically, map
475 indicator = ' ' to ''.  This is for the convenience of a cataloger
476 using a mouse to select an indicator input.
477
478 =cut
479
480 sub format_indicator {
481     my $ind_value = shift;
482     return '' if not defined $ind_value;
483     return '' if $ind_value eq ' ';
484     return $ind_value;
485 }
486
487 sub build_tabs {
488     my ( $template, $record, $dbh, $encoding,$input ) = @_;
489
490     # fill arrays
491     my @loop_data = ();
492     my $tag;
493
494     my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
495     my $query = "SELECT authorised_value, lib
496                 FROM authorised_values";
497     $query .= qq{ LEFT JOIN authorised_values_branches ON ( id = av_id )} if $branch_limit;
498     $query .= " WHERE category = ?";
499     $query .= " AND ( branchcode = ? OR branchcode IS NULL )" if $branch_limit;
500     $query .= " GROUP BY lib ORDER BY lib, lib_opac";
501     my $authorised_values_sth = $dbh->prepare( $query );
502
503     # in this array, we will push all the 10 tabs
504     # to avoid having 10 tabs in the template : they will all be in the same BIG_LOOP
505     my @BIG_LOOP;
506     my %seen;
507     my @tab_data; # all tags to display
508     
509     foreach my $used ( @$usedTagsLib ){
510         push @tab_data,$used->{tagfield} if not $seen{$used->{tagfield}};
511         $seen{$used->{tagfield}}++;
512     }
513         
514     my $max_num_tab=-1;
515     foreach(@$usedTagsLib){
516         if($_->{tab} > -1 && $_->{tab} >= $max_num_tab && $_->{tagfield} != '995'){ # FIXME : MARC21 ?
517             $max_num_tab = $_->{tab}; 
518         }
519     }
520     if($max_num_tab >= 9){
521         $max_num_tab = 9;
522     }
523     # loop through each tab 0 through 9
524     for ( my $tabloop = 0 ; $tabloop <= $max_num_tab ; $tabloop++ ) {
525         my @loop_data = (); #innerloop in the template.
526         my $i = 0;
527         foreach my $tag (@tab_data) {
528             $i++;
529             next if ! $tag;
530             my ($indicator1, $indicator2);
531             my $index_tag = CreateKey;
532
533             # if MARC::Record is not empty =>use it as master loop, then add missing subfields that should be in the tab.
534             # if MARC::Record is empty => use tab as master loop.
535             if ( $record ne -1 && ( $record->field($tag) || $tag eq '000' ) ) {
536                 my @fields;
537                 if ( $tag ne '000' ) {
538                     @fields = $record->field($tag);
539                 }
540                 else {
541                    push @fields, $record->leader(); # if tag == 000
542                 }
543                 # loop through each field
544                 foreach my $field (@fields) {
545                     
546                     my @subfields_data;
547                     if ( $tag < 10 ) {
548                         my ( $value, $subfield );
549                         if ( $tag ne '000' ) {
550                             $value    = $field->data();
551                             $subfield = "@";
552                         }
553                         else {
554                             $value    = $field;
555                             $subfield = '@';
556                         }
557                         next if ( $tagslib->{$tag}->{$subfield}->{tab} ne $tabloop );
558                         next
559                           if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq
560                             'biblio.biblionumber' );
561                         push(
562                             @subfields_data,
563                             &create_input(
564                                 $tag, $subfield, $value, $index_tag, $tabloop, $record,
565                                 $authorised_values_sth,$input
566                             )
567                         );
568                     }
569                     else {
570                         my @subfields = $field->subfields();
571                         foreach my $subfieldcount ( 0 .. $#subfields ) {
572                             my $subfield = $subfields[$subfieldcount][0];
573                             my $value    = $subfields[$subfieldcount][1];
574                             next if ( length $subfield != 1 );
575                             next if ( $tagslib->{$tag}->{$subfield}->{tab} ne $tabloop );
576                             push(
577                                 @subfields_data,
578                                 &create_input(
579                                     $tag, $subfield, $value, $index_tag, $tabloop,
580                                     $record, $authorised_values_sth,$input
581                                 )
582                             );
583                         }
584                     }
585
586                     # now, loop again to add parameter subfield that are not in the MARC::Record
587                     foreach my $subfield ( sort( keys %{ $tagslib->{$tag} } ) )
588                     {
589                         next if ( length $subfield != 1 );
590                         next if ( $tagslib->{$tag}->{$subfield}->{tab} ne $tabloop );
591                         next if ( $tag < 10 );
592                         next
593                           if ( ( $tagslib->{$tag}->{$subfield}->{hidden} <= -4 )
594                             or ( $tagslib->{$tag}->{$subfield}->{hidden} >= 5 ) )
595                             and not ( $subfield eq "9" and
596                                       exists($tagslib->{$tag}->{'a'}->{authtypecode}) and
597                                       defined($tagslib->{$tag}->{'a'}->{authtypecode}) and
598                                       $tagslib->{$tag}->{'a'}->{authtypecode} ne ""
599                                     )
600                           ;    #check for visibility flag
601                                # if subfield is $9 in a field whose $a is authority-controlled,
602                                # always include in the form regardless of the hidden setting - bug 2206
603                         next if ( defined( $field->subfield($subfield) ) );
604                         push(
605                             @subfields_data,
606                             &create_input(
607                                 $tag, $subfield, '', $index_tag, $tabloop, $record,
608                                 $authorised_values_sth,$input
609                             )
610                         );
611                     }
612                     if ( $#subfields_data >= 0 ) {
613                         # build the tag entry.
614                         # note that the random() field is mandatory. Otherwise, on repeated fields, you'll 
615                         # have twice the same "name" value, and cgi->param() will return only one, making
616                         # all subfields to be merged in a single field.
617                         my %tag_data = (
618                             tag           => $tag,
619                             index         => $index_tag,
620                             tag_lib       => $tagslib->{$tag}->{lib},
621                             repeatable       => $tagslib->{$tag}->{repeatable},
622                             mandatory       => $tagslib->{$tag}->{mandatory},
623                             subfield_loop => \@subfields_data,
624                             fixedfield    => $tag < 10?1:0,
625                             random        => CreateKey,
626                         );
627                         if ($tag >= 10){ # no indicator for 00x tags
628                            $tag_data{indicator1} = format_indicator($field->indicator(1)),
629                            $tag_data{indicator2} = format_indicator($field->indicator(2)),
630                         }
631                         push( @loop_data, \%tag_data );
632                     }
633                  } # foreach $field end
634
635             # if breeding is empty
636             }
637             else {
638                 my @subfields_data;
639                 foreach my $subfield ( sort( keys %{ $tagslib->{$tag} } ) ) {
640                     next if ( length $subfield != 1 );
641                     next
642                       if ( ( $tagslib->{$tag}->{$subfield}->{hidden} <= -4 )
643                         or ( $tagslib->{$tag}->{$subfield}->{hidden} >= 5 ) )
644                       and not ( $subfield eq "9" and
645                                 exists($tagslib->{$tag}->{'a'}->{authtypecode}) and
646                                 defined($tagslib->{$tag}->{'a'}->{authtypecode}) and
647                                 $tagslib->{$tag}->{'a'}->{authtypecode} ne ""
648                               )
649                       ;    #check for visibility flag
650                            # if subfield is $9 in a field whose $a is authority-controlled,
651                            # always include in the form regardless of the hidden setting - bug 2206
652                     next
653                       if ( $tagslib->{$tag}->{$subfield}->{tab} ne $tabloop );
654                         push(
655                         @subfields_data,
656                         &create_input(
657                             $tag, $subfield, '', $index_tag, $tabloop, $record,
658                             $authorised_values_sth,$input
659                         )
660                     );
661                 }
662                 if ( $#subfields_data >= 0 ) {
663                     my %tag_data = (
664                         tag              => $tag,
665                         index            => $index_tag,
666                         tag_lib          => $tagslib->{$tag}->{lib},
667                         repeatable       => $tagslib->{$tag}->{repeatable},
668                         mandatory       => $tagslib->{$tag}->{mandatory},
669                         indicator1       => $indicator1,
670                         indicator2       => $indicator2,
671                         subfield_loop    => \@subfields_data,
672                         tagfirstsubfield => $subfields_data[0],
673                         fixedfield       => $tag < 10?1:0,
674                     );
675                     
676                     push @loop_data, \%tag_data ;
677                 }
678             }
679         }
680         if ( $#loop_data >= 0 ) {
681             push @BIG_LOOP, {
682                 number    => $tabloop,
683                 innerloop => \@loop_data,
684             };
685         }
686     }
687     $authorised_values_sth->finish;
688     $template->param( BIG_LOOP => \@BIG_LOOP );
689 }
690
691 # ========================
692 #          MAIN
693 #=========================
694 my $input = new CGI;
695 my $error = $input->param('error');
696 my $biblionumber  = $input->param('biblionumber'); # if biblionumber exists, it's a modif, not a new biblio.
697 my $parentbiblio  = $input->param('parentbiblionumber');
698 my $breedingid    = $input->param('breedingid');
699 my $z3950         = $input->param('z3950');
700 my $op            = $input->param('op');
701 my $mode          = $input->param('mode');
702 my $frameworkcode = $input->param('frameworkcode');
703 my $redirect      = $input->param('redirect');
704 my $searchid      = $input->param('searchid');
705 my $dbh           = C4::Context->dbh;
706 my $hostbiblionumber = $input->param('hostbiblionumber');
707 my $hostitemnumber = $input->param('hostitemnumber');
708 # fast cataloguing datas in transit
709 my $fa_circborrowernumber = $input->param('circborrowernumber');
710 my $fa_barcode            = $input->param('barcode');
711 my $fa_branch             = $input->param('branch');
712 my $fa_stickyduedate      = $input->param('stickyduedate');
713 my $fa_duedatespec        = $input->param('duedatespec');
714
715 my $userflags = 'edit_catalogue';
716
717 my $changed_framework = $input->param('changed_framework');
718 $frameworkcode = &GetFrameworkCode($biblionumber)
719   if ( $biblionumber and not($frameworkcode) and $op ne 'addbiblio' );
720
721 if ($frameworkcode eq 'FA'){
722     $userflags = 'fast_cataloging';
723 }
724
725 $frameworkcode = '' if ( $frameworkcode eq 'Default' );
726 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
727     {
728         template_name   => "cataloguing/addbiblio.tt",
729         query           => $input,
730         type            => "intranet",
731         authnotrequired => 0,
732         flagsrequired   => { editcatalogue => $userflags },
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 ( 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 }
751
752 my $frameworkcodeloop = Koha::BiblioFrameworks->search({}, { order_by => ['frameworktext'] });
753 $template->param( frameworkcodeloop => $frameworkcodeloop ,
754         breedingid => $breedingid );
755
756 # ++ Global
757 $tagslib         = &GetMarcStructure( 1, $frameworkcode );
758 $usedTagsLib     = &GetUsedMarcStructure( $frameworkcode );
759 $mandatory_z3950 = GetMandatoryFieldZ3950($frameworkcode);
760 # -- Global
761
762 my $record   = -1;
763 my $encoding = "";
764 my (
765         $biblionumbertagfield,
766         $biblionumbertagsubfield,
767         $biblioitemnumtagfield,
768         $biblioitemnumtagsubfield,
769         $biblioitemnumber
770 );
771
772 if (($biblionumber) && !($breedingid)){
773         $record = GetMarcBiblio($biblionumber);
774 }
775 if ($breedingid) {
776     ( $record, $encoding ) = MARCfindbreeding( $breedingid ) ;
777 }
778
779 #populate hostfield if hostbiblionumber is available
780 if ($hostbiblionumber) {
781     my $marcflavour = C4::Context->preference("marcflavour");
782     $record = MARC::Record->new();
783     $record->leader('');
784     my $field =
785       PrepHostMarcField( $hostbiblionumber, $hostitemnumber, $marcflavour );
786     $record->append_fields($field);
787 }
788
789 # This is  a child record
790 if ($parentbiblio) {
791     my $marcflavour = C4::Context->preference('marcflavour');
792     $record = MARC::Record->new();
793     SetMarcUnicodeFlag($record, $marcflavour);
794     my $hostfield = prepare_host_field($parentbiblio,$marcflavour);
795     if ($hostfield) {
796         $record->append_fields($hostfield);
797     }
798 }
799
800 $is_a_modif = 0;
801     
802 if ($biblionumber) {
803     $is_a_modif = 1;
804     my $title = C4::Context->preference('marcflavour') eq "UNIMARC" ? $record->subfield('200', 'a') : $record->title;
805     $template->param( title => $title );
806
807     # if it's a modif, retrieve bibli and biblioitem numbers for the future modification of old-DB.
808     ( $biblionumbertagfield, $biblionumbertagsubfield ) =
809         &GetMarcFromKohaField( "biblio.biblionumber", $frameworkcode );
810     ( $biblioitemnumtagfield, $biblioitemnumtagsubfield ) =
811         &GetMarcFromKohaField( "biblioitems.biblioitemnumber", $frameworkcode );
812             
813     # search biblioitems value
814     my $sth =  $dbh->prepare("select biblioitemnumber from biblioitems where biblionumber=?");
815     $sth->execute($biblionumber);
816     ($biblioitemnumber) = $sth->fetchrow;
817 }
818
819 #-------------------------------------------------------------------------------------
820 if ( $op eq "addbiblio" ) {
821 #-------------------------------------------------------------------------------------
822     $template->param(
823         biblionumberdata => $biblionumber,
824     );
825     # getting html input
826     my @params = $input->multi_param();
827     $record = TransformHtmlToMarc( $input, 1 );
828     # check for a duplicate
829     my ( $duplicatebiblionumber, $duplicatetitle );
830     if ( !$is_a_modif ) {
831         ( $duplicatebiblionumber, $duplicatetitle ) = FindDuplicate($record);
832     }
833     my $confirm_not_duplicate = $input->param('confirm_not_duplicate');
834     # it is not a duplicate (determined either by Koha itself or by user checking it's not a duplicate)
835     if ( !$duplicatebiblionumber or $confirm_not_duplicate ) {
836         my $oldbibitemnum;
837         if (C4::Context->preference("BiblioAddsAuthorities")){
838             BiblioAutoLink( $record, $frameworkcode );
839         } 
840         if ( $is_a_modif ) {
841             ModBiblioframework( $biblionumber, $frameworkcode ); 
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;