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