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