partial 1481: adding to templates, fixing non-display of data
[koha.git] / cataloguing / addbiblio.pl
1 #!/usr/bin/perl 
2
3 # $Id$
4
5 # Copyright 2000-2002 Katipo Communications
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 with
19 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
20 # Suite 330, Boston, MA  02111-1307 USA
21
22 use strict;
23 use CGI;
24 use C4::Output;
25 use C4::Auth;
26 use C4::Biblio;
27 use C4::Search;
28 use C4::AuthoritiesMarc;
29 use C4::Context;
30 use MARC::Record;
31 use C4::Log;
32 use C4::Koha;    # XXX subfield_is_koha_internal_p
33 use Date::Calc qw(Today);
34 use MARC::File::USMARC;
35 use MARC::File::XML;
36
37 if ( C4::Context->preference('marcflavour') eq 'UNIMARC' ) {
38     MARC::File::XML->default_record_format('UNIMARC');
39 }
40
41 our($tagslib,$authorised_values_sth,$is_a_modif,$usedTagsLib,$mandatory_z3950);
42
43 =item MARCfindbreeding
44
45     $record = MARCfindbreeding($dbh, $breedingid);
46
47 Look up the breeding farm with database handle $dbh, for the
48 record with id $breedingid.  If found, returns the decoded
49 MARC::Record; otherwise, -1 is returned (FIXME).
50 Returns as second parameter the character encoding.
51
52 =cut
53
54 sub MARCfindbreeding {
55     my ( $dbh, $id ) = @_;
56     my $sth =
57       $dbh->prepare("select file,marc,encoding from marc_breeding where id=?");
58     $sth->execute($id);
59     my ( $file, $marc, $encoding ) = $sth->fetchrow;
60     if ($marc) {
61         my $record = MARC::Record->new_from_usmarc($marc);
62         if ( $record->field('010') ) {
63             foreach my $field ( $record->field('010') ) {
64                 foreach my $subfield ( $field->subfield('a') ) {
65                     my $newisbn = $field->subfield('a');
66                     $newisbn =~ s/-//g;
67                     $field->update( 'a' => $newisbn );
68                 }
69                 # record->insert_fields_ordered($record->field('010'));
70             }
71         }
72
73         if ($record->subfield(100,'a')) {
74             my $f100a=$record->subfield(100,'a');
75             my $f100 = $record->field(100);
76             my $f100temp = $f100->as_string;
77             $record->delete_field($f100);
78             if ( length($f100temp) > 28 ) {
79                 substr( $f100temp, 26, 2, "50" );
80                 $f100->update( 'a' => $f100temp );
81                 my $f100 = MARC::Field->new( '100', '', '', 'a' => $f100temp );
82                 $record->insert_fields_ordered($f100);
83             }
84         }
85                 
86         if ( ref($record) eq undef ) {
87             return -1;
88         }
89         else {
90             if (    C4::Context->preference("z3950NormalizeAuthor")
91                 and C4::Context->preference("z3950AuthorAuthFields") )
92             {
93                 my ( $tag, $subfield ) = GetMarcFromKohaField("biblio.author");
94
95  #                 my $summary = C4::Context->preference("z3950authortemplate");
96                 my $auth_fields =
97                   C4::Context->preference("z3950AuthorAuthFields");
98                 my @auth_fields = split /,/, $auth_fields;
99                 my $field;
100
101                 if ( $record->field($tag) ) {
102                     foreach my $tmpfield ( $record->field($tag)->subfields ) {
103
104        #                        foreach my $subfieldcode ($tmpfield->subfields){
105                         my $subfieldcode  = shift @$tmpfield;
106                         my $subfieldvalue = shift @$tmpfield;
107                         if ($field) {
108                             $field->add_subfields(
109                                 "$subfieldcode" => $subfieldvalue )
110                               if ( $subfieldcode ne $subfield );
111                         }
112                         else {
113                             $field =
114                               MARC::Field->new( $tag, "", "",
115                                 $subfieldcode => $subfieldvalue )
116                               if ( $subfieldcode ne $subfield );
117                         }
118                     }
119                 }
120                 $record->delete_field( $record->field($tag) );
121                 foreach my $fieldtag (@auth_fields) {
122                     next unless ( $record->field($fieldtag) );
123                     my $lastname  = $record->field($fieldtag)->subfield('a');
124                     my $firstname = $record->field($fieldtag)->subfield('b');
125                     my $title     = $record->field($fieldtag)->subfield('c');
126                     my $number    = $record->field($fieldtag)->subfield('d');
127                     if ($title) {
128
129 #                         $field->add_subfields("$subfield"=>"[ ".ucfirst($title).ucfirst($firstname)." ".$number." ]");
130                         $field->add_subfields(
131                                 "$subfield" => ucfirst($title) . " "
132                               . ucfirst($firstname) . " "
133                               . $number );
134                     }
135                     else {
136
137 #                       $field->add_subfields("$subfield"=>"[ ".ucfirst($firstname).", ".ucfirst($lastname)." ]");
138                         $field->add_subfields(
139                             "$subfield" => ucfirst($firstname) . ", "
140                               . ucfirst($lastname) );
141                     }
142                 }
143                 $record->insert_fields_ordered($field);
144             }
145             return $record, $encoding;
146         }
147     }
148     return -1;
149 }
150
151 =item build_authorized_values_list
152
153 =cut
154
155 sub build_authorized_values_list ($$$$$$$) {
156     my ( $tag, $subfield, $value, $dbh, $authorised_values_sth,$index_tag,$index_subfield ) = @_;
157
158     my @authorised_values;
159     my %authorised_lib;
160
161     # builds list, depending on authorised value...
162
163     #---- branch
164     if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
165         my $sth =
166           $dbh->prepare(
167             "select branchcode,branchname from branches order by branchname");
168         $sth->execute;
169         push @authorised_values, ""
170           unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
171
172         while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
173             push @authorised_values, $branchcode;
174             $authorised_lib{$branchcode} = $branchname;
175         }
176
177         #----- itemtypes
178     }
179     elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
180         my $sth =
181           $dbh->prepare(
182             "select itemtype,description from itemtypes order by description");
183         $sth->execute;
184         push @authorised_values, ""
185           unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
186           
187         my $itemtype;
188         
189         while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
190             push @authorised_values, $itemtype;
191             $authorised_lib{$itemtype} = $description;
192         }
193         $value = $itemtype unless ($value);
194
195         #---- "true" authorised value
196     }
197     else {
198         $authorised_values_sth->execute(
199             $tagslib->{$tag}->{$subfield}->{authorised_value} );
200
201         push @authorised_values, ""
202           unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
203
204         while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
205             push @authorised_values, $value;
206             $authorised_lib{$value} = $lib;
207         }
208     }
209     return CGI::scrolling_list(
210         -name     => "tag_".$tag."_subfield_".$subfield."_".$index_tag."_".$index_subfield,
211         -values   => \@authorised_values,
212         -default  => $value,
213         -labels   => \%authorised_lib,
214         -override => 1,
215         -size     => 1,
216         -multiple => 0,
217         -tabindex => 1,
218         -id       => "tag_".$tag."_subfield_".$subfield."_".$index_tag."_".$index_subfield,
219         -class    => "input_marceditor",
220     );
221 }
222
223 =item CreateKey
224
225     Create a random value to set it into the input name
226
227 =cut
228
229 sub CreateKey(){
230     return int(rand(1000000));
231 }
232
233 =item GetMandatoryFieldZ3950
234
235     This function return an hashref which containts all mandatory field
236     to search with z3950 server.
237     
238 =cut
239
240 sub GetMandatoryFieldZ3950($){
241     my $frameworkcode = shift;
242     my @isbn   = GetMarcFromKohaField('biblioitems.isbn',$frameworkcode);
243     my @title  = GetMarcFromKohaField('biblio.title',$frameworkcode);
244     my @author = GetMarcFromKohaField('biblio.author',$frameworkcode);
245     my @issn   = GetMarcFromKohaField('biblioitems.issn',$frameworkcode);
246     
247     return {
248         $isbn[0].$isbn[1]     => 'isbn',
249         $title[0].$title[1]   => 'title',
250         $author[0].$author[1] => 'author',
251         $issn[0].$issn[1]     => 'issn',
252     };
253 }
254
255 =item create_input
256
257  builds the <input ...> entry for a subfield.
258
259 =cut
260
261 sub create_input {
262     my ( $tag, $subfield, $value, $index_tag, $tabloop, $rec, $authorised_values_sth,$cgi ) = @_;
263     
264     my $index_subfield = CreateKey(); # create a specifique key for each subfield
265
266     $value =~ s/"/&quot;/g;
267
268     # if there is no value provided but a default value in parameters, get it
269     unless ($value) {
270         $value = $tagslib->{$tag}->{$subfield}->{defaultvalue};
271
272         # get today date & replace YYYY, MM, DD if provided in the default value
273         my ( $year, $month, $day ) = Today();
274         $month = sprintf( "%02d", $month );
275         $day   = sprintf( "%02d", $day );
276         $value =~ s/YYYY/$year/g;
277         $value =~ s/MM/$month/g;
278         $value =~ s/DD/$day/g;
279     }
280     my $dbh = C4::Context->dbh;
281     my %subfield_data = (
282         tag        => $tag,
283         subfield   => $subfield,
284         marc_lib   => substr( $tagslib->{$tag}->{$subfield}->{lib}, 0, 22 ),
285         marc_lib_plain => $tagslib->{$tag}->{$subfield}->{lib}, 
286         tag_mandatory  => $tagslib->{$tag}->{mandatory},
287         mandatory      => $tagslib->{$tag}->{$subfield}->{mandatory},
288         repeatable     => $tagslib->{$tag}->{$subfield}->{repeatable},
289         kohafield      => $tagslib->{$tag}->{$subfield}->{kohafield},
290         index          => $index_tag,
291         id             => "tag_".$tag."_subfield_".$subfield."_".$index_tag."_".$index_subfield,
292         value          => $value,
293         random         => CreateKey(),
294     );
295     # deal with a <010 tag
296     if($subfield eq '@'){
297         $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_tag."_".$index_subfield;
298     } else {
299          $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".$index_tag."_".$index_subfield;
300     }
301
302     if(exists $mandatory_z3950->{$tag.$subfield}){
303         $subfield_data{z3950_mandatory} = $mandatory_z3950->{$tag.$subfield};
304     }
305     # decide if the subfield must be expanded (visible) by default or not
306     # if it is mandatory, then expand. If it is hidden explicitly by the hidden flag, hidden anyway
307     $subfield_data{visibility} = "display:none;"
308         if (    ($tagslib->{$tag}->{$subfield}->{hidden} % 2 == 1) and $value ne ''
309             or ($value eq '' and !$tagslib->{$tag}->{$subfield}->{mandatory})
310         );
311     # always expand all subfields of a mandatory field
312     $subfield_data{visibility} = "" if $tagslib->{$tag}->{mandatory};
313     # it's an authorised field
314     if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
315         $subfield_data{marc_value} =
316           build_authorized_values_list( $tag, $subfield, $value, $dbh,
317             $authorised_values_sth,$index_tag,$index_subfield );
318
319     # it's a thesaurus / authority field
320     }
321     elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode} ) {
322         $subfield_data{marc_value} =
323             "<input type=\"text\"
324                     id=\"".$subfield_data{id}."\"
325                     name=\"".$subfield_data{id}."\"
326                     value=\"$value\"
327                     class=\"input_marceditor\"
328                     tabindex=\"1\"
329                     \/>
330                     <span class=\"buttonDot\"
331                         onclick=\"Dopop('/cgi-bin/koha/authorities/auth_finder.pl?authtypecode=".$tagslib->{$tag}->{$subfield}->{authtypecode}."&index=$subfield_data{id}','$subfield_data{id}')\">...</span>
332                 ";
333     # it's a plugin field
334     }
335     elsif ( $tagslib->{$tag}->{$subfield}->{'value_builder'} ) {
336
337         # opening plugin. Just check wether we are on a developper computer on a production one
338         # (the cgidir differs)
339         my $cgidir = C4::Context->intranetdir . "/cgi-bin/cataloguing/value_builder";
340         unless ( opendir( DIR, "$cgidir" ) ) {
341             $cgidir = C4::Context->intranetdir . "/cataloguing/value_builder";
342         }
343         my $plugin = $cgidir . "/" . $tagslib->{$tag}->{$subfield}->{'value_builder'};
344         do $plugin || die "Plugin Failed: ".$plugin;
345         my $extended_param = plugin_parameters( $dbh, $rec, $tagslib, $subfield_data{id}, $tabloop );
346         my ( $function_name, $javascript ) = plugin_javascript( $dbh, $rec, $tagslib, $subfield_data{id}, $tabloop );
347 #         my ( $function_name, $javascript,$extended_param );
348         
349         $subfield_data{marc_value} =
350                 "<input tabindex=\"1\"
351                         type=\"text\"
352                         id=\"".$subfield_data{id}."\"
353                         name=\"".$subfield_data{id}."\"
354                         value=\"$value\"
355                         class=\"input_marceditor\"
356                         onfocus=\"Focus$function_name($index_tag)\"
357                         onblur=\"Blur$function_name($index_tag); \" \/>
358                 <span class=\"buttonDot\" onclick=\"Clic$function_name('$subfield_data{id}')\">...</a>
359                 $javascript";
360         # it's an hidden field
361     }
362     elsif ( $tag eq '' ) {
363         $subfield_data{marc_value} =
364             "<input tabindex=\"1\"
365                     type=\"hidden\"
366                     id=\"".$subfield_data{id}."\"
367                     name=\"".$subfield_data{id}."\"
368                     value=\"$value\" \/>
369             ";
370     }
371     elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) {
372         $subfield_data{marc_value} =
373             "<input type=\"text\"
374                     id=\"".$subfield_data{id}."\"
375                     name=\"".$subfield_data{id}."\"
376                     class=\"input_marceditor\"
377                     tabindex=\"1\"
378                     value=\"$value\"
379             \/>";
380
381         # it's a standard field
382     }
383     else {
384         if (
385             length($value) > 100
386             or
387             ( C4::Context->preference("marcflavour") eq "UNIMARC" && $tag >= 300
388                 and $tag < 400 && $subfield eq 'a' )
389             or (    $tag >= 500
390                 and $tag < 600
391                 && C4::Context->preference("marcflavour") eq "MARC21" )
392           )
393         {
394             $subfield_data{marc_value} =
395                 "<textarea cols=\"70\"
396                            rows=\"4\"
397                            id=\"".$subfield_data{id}."\"
398                            name=\"".$subfield_data{id}."\"
399                            class=\"input_marceditor\"
400                            tabindex=\"1\"
401                            >$value</textarea>
402                 ";
403         }
404         else {
405             $subfield_data{marc_value} =
406                 "<input type=\"text\"
407                         id=\"".$subfield_data{id}."\"
408                         name=\"".$subfield_data{id}."\"
409                         value=\"$value\"
410                         tabindex=\"1\"
411                         class=\"input_marceditor\"
412                 \/>
413                 ";
414         }
415     }
416     $subfield_data{'index_subfield'} = $index_subfield;
417     return \%subfield_data;
418 }
419
420 sub build_tabs ($$$$$) {
421     my ( $template, $record, $dbh, $encoding,$input ) = @_;
422
423     # fill arrays
424     my @loop_data = ();
425     my $tag;
426
427     my $authorised_values_sth = $dbh->prepare(
428         "select authorised_value,lib
429         from authorised_values
430         where category=? order by lib"
431     );
432     
433     # in this array, we will push all the 10 tabs
434     # to avoid having 10 tabs in the template : they will all be in the same BIG_LOOP
435     my @BIG_LOOP;
436     my %seen;
437     my @tab_data; # all tags to display
438     
439     foreach my $used ( @$usedTagsLib ){
440         push @tab_data,$used->{tagfield} if not $seen{$used->{tagfield}};
441         $seen{$used->{tagfield}}++;
442     }
443         
444     my $max_num_tab=-1;
445     foreach(@$usedTagsLib){
446         if($_->{tab} > -1 && $_->{tab} >= $max_num_tab && $_->{tagfield} != '995'){ # FIXME : MARC21 ?
447             $max_num_tab = $_->{tab}; 
448         }
449     }
450     if($max_num_tab >= 9){
451         $max_num_tab = 9;
452     }
453     # loop through each tab 0 through 9
454     for ( my $tabloop = 0 ; $tabloop <= $max_num_tab ; $tabloop++ ) {
455         my @loop_data = (); #innerloop in the template.
456         my $i = 0;
457         foreach my $tag (@tab_data) {
458             $i++;
459             next if ! $tag;
460             my $indicator;
461             my $index_tag = CreateKey;
462
463             # if MARC::Record is not empty =>use it as master loop, then add missing subfields that should be in the tab.
464             # if MARC::Record is empty => use tab as master loop.
465             if ( $record ne -1 && ( $record->field($tag) || $tag eq '000' ) ) {
466                 my @fields;
467                 if ( $tag ne '000' ) {
468                     @fields = $record->field($tag);
469                 }
470                 else {
471                    push @fields, $record->leader(); # if tag == 000
472                 }
473                 # loop through each field
474                 foreach my $field (@fields) {
475                     
476                     my @subfields_data;
477                     if ( $tag < 10 ) {
478                         my ( $value, $subfield );
479                         if ( $tag ne '000' ) {
480                             $value    = $field->data();
481                             $subfield = "@";
482                         }
483                         else {
484                             $value    = $field;
485                             $subfield = '@';
486                         }
487                         next if ( $tagslib->{$tag}->{$subfield}->{tab} ne $tabloop );
488                         next
489                           if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq
490                             'biblio.biblionumber' );
491                         push(
492                             @subfields_data,
493                             &create_input(
494                                 $tag, $subfield, $value, $index_tag, $tabloop, $record,
495                                 $authorised_values_sth,$input
496                             )
497                         );
498                     }
499                     else {
500                         my @subfields = $field->subfields();
501                         foreach my $subfieldcount ( 0 .. $#subfields ) {
502                             my $subfield = $subfields[$subfieldcount][0];
503                             my $value    = $subfields[$subfieldcount][1];
504                             next if ( length $subfield != 1 );
505                             next if ( $tagslib->{$tag}->{$subfield}->{tab} ne $tabloop );
506                             push(
507                                 @subfields_data,
508                                 &create_input(
509                                     $tag, $subfield, $value, $index_tag, $tabloop,
510                                     $record, $authorised_values_sth,$input
511                                 )
512                             );
513                         }
514                     }
515
516                     # now, loop again to add parameter subfield that are not in the MARC::Record
517                     foreach my $subfield ( sort( keys %{ $tagslib->{$tag} } ) )
518                     {
519                         next if ( length $subfield != 1 );
520                         next if ( $tagslib->{$tag}->{$subfield}->{tab} ne $tabloop );
521                         next if ( $tag < 10 );
522                         next
523                           if ( ( $tagslib->{$tag}->{$subfield}->{hidden} <= -4 )
524                             or ( $tagslib->{$tag}->{$subfield}->{hidden} >= 5 )
525                           );    #check for visibility flag
526                         next if ( defined( $field->subfield($subfield) ) );
527                         push(
528                             @subfields_data,
529                             &create_input(
530                                 $tag, $subfield, '', $index_tag, $tabloop, $record,
531                                 $authorised_values_sth,$input
532                             )
533                         );
534                     }
535                     if ( $#subfields_data >= 0 ) {
536                         # build the tag entry.
537                         # note that the random() field is mandatory. Otherwise, on repeated fields, you'll 
538                         # have twice the same "name" value, and cgi->param() will return only one, making
539                         # all subfields to be merged in a single field.
540                         my %tag_data = (
541                             tag           => $tag,
542                             index         => $index_tag,
543                             tag_lib       => $tagslib->{$tag}->{lib},
544                             repeatable       => $tagslib->{$tag}->{repeatable},
545                             subfield_loop => \@subfields_data,
546                             fixedfield    => $tag < 10?1:0,
547                             random        => CreateKey,
548                         );
549                         if ($tag >= 010){ # no indicator for theses tag
550                            $tag_data{indicator} = $field->indicator(1).$field->indicator(2);
551                         }
552                         push( @loop_data, \%tag_data );
553                     }
554                  } # foreach $field end
555
556             # if breeding is empty
557             }
558             else {
559                 my @subfields_data;
560                 foreach my $subfield ( sort( keys %{ $tagslib->{$tag} } ) ) {
561                     next if ( length $subfield != 1 );
562                     next
563                       if ( ( $tagslib->{$tag}->{$subfield}->{hidden} <= -5 )
564                         or ( $tagslib->{$tag}->{$subfield}->{hidden} >= 4 ) )
565                       ;    #check for visibility flag
566                     next
567                       if ( $tagslib->{$tag}->{$subfield}->{tab} ne $tabloop );
568                     push(
569                         @subfields_data,
570                         &create_input(
571                             $tag, $subfield, '', $index_tag, $tabloop, $record,
572                             $authorised_values_sth,$input
573                         )
574                     );
575                 }
576                 if ( $#subfields_data >= 0 ) {
577                     my %tag_data = (
578                         tag              => $tag,
579                         index            => $index_tag,
580                         tag_lib          => $tagslib->{$tag}->{lib},
581                         repeatable       => $tagslib->{$tag}->{repeatable},
582                         indicator        => $indicator,
583                         subfield_loop    => \@subfields_data,
584                         tagfirstsubfield => $subfields_data[0],
585                         fixedfield       => $tag < 10?1:0,
586                     );
587                     
588                     push @loop_data, \%tag_data ;
589                 }
590             }
591         }
592         if ( $#loop_data >= 0 ) {
593             push @BIG_LOOP, {
594                 number    => $tabloop,
595                 innerloop => \@loop_data,
596             };
597         }
598     }
599     $template->param( BIG_LOOP => \@BIG_LOOP );
600 }
601
602 sub BiblioAddAuthorities{
603   my ( $record, $frameworkcode ) = @_;
604   my $dbh=C4::Context->dbh;
605   my $query=$dbh->prepare(qq|
606 SELECT authtypecode,tagfield
607 FROM marc_subfield_structure 
608 WHERE frameworkcode=? 
609 AND (authtypecode IS NOT NULL AND authtypecode<>\"\")|);
610 # SELECT authtypecode,tagfield
611 # FROM marc_subfield_structure 
612 # WHERE frameworkcode=? 
613 # AND (authtypecode IS NOT NULL OR authtypecode<>\"\")|);
614   $query->execute($frameworkcode);
615   my ($countcreated,$countlinked);
616   while (my $data=$query->fetchrow_hashref){
617     if ($record->field($data->{tagfield})){
618       next if ($record->subfield($data->{tagfield},'3')||$record->subfield($data->{tagfield},'9'));
619       # No authorities id in the tag.
620       # Search if there is any authorities to link to.
621       my $query='at='.$data->{authtypecode}.' ';
622       map {$query.= " and he=".$_->[1] if ($_->[0]=~/[A-z]/)}  $record->field($data->{tagfield})->subfields();
623       my ($error,$results)=SimpleSearch($query,"authorityserver");
624     # there is at least 1 result => return the 1st one
625       if (@$results>1) {
626         my $marcrecord = MARC::File::USMARC::decode($results->[0]);
627         $record->field($data->{tagfield})->add_subfields('9'=>$marcrecord->field('001')->data);
628   $countlinked++;
629       } else {
630   #There are no results, build authority record, add it to Authorities, get authid and add it to 9
631   ###NOTICE : This is only valid if a subfield is linked to one and only one authtypecode
632      
633         my $authtypedata=GetAuthType($data->{authtypecode});
634         my $marcrecordauth=MARC::Record->new();
635         my $field=MARC::Field->new($authtypedata->{auth_tag_to_report},'','',"a"=>"".$record->subfield($data->{tagfield},'a'));
636         map { $field->add_subfields($_->[0]=>$_->[1]) if ($_->[0]=~/[A-z]/ && $_->[0] ne "a" )}  $record->field($data->{tagfield})->subfields();
637         $marcrecordauth->insert_fields_ordered($field);
638         my $authid=AddAuthority($marcrecordauth,'',$data->{authtypecode});
639         $countcreated++;
640         $record->field($data->{tagfield})->add_subfields('9'=>$authid);
641       }
642     }  
643   }
644   return ($countlinked,$countcreated);
645 }
646
647 # ========================
648 #          MAIN
649 #=========================
650 my $input = new CGI;
651 my $error = $input->param('error');
652 my $biblionumber  = $input->param('biblionumber'); # if biblionumber exists, it's a modif, not a new biblio.
653 my $breedingid    = $input->param('breedingid');
654 my $z3950         = $input->param('z3950');
655 my $op            = $input->param('op');
656 my $mode          = $input->param('mode');
657 my $frameworkcode = $input->param('frameworkcode');
658 my $dbh           = C4::Context->dbh;
659
660 $frameworkcode = &GetFrameworkCode($biblionumber)
661   if ( $biblionumber and not($frameworkcode) );
662
663 $frameworkcode = '' if ( $frameworkcode eq 'Default' );
664 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
665     {
666         template_name   => "cataloguing/addbiblio.tmpl",
667         query           => $input,
668         type            => "intranet",
669         authnotrequired => 0,
670         flagsrequired   => { editcatalogue => 1 },
671     }
672 );
673
674 #Getting the list of all frameworks
675 my $queryfwk = $dbh->prepare("select frameworktext, frameworkcode from biblio_framework");
676 $queryfwk->execute;
677 my %select_fwk;
678 my @select_fwk;
679 my $curfwk;
680 push @select_fwk, "Default";
681 $select_fwk{"Default"} = "Default";
682
683 while ( my ( $description, $fwk ) = $queryfwk->fetchrow ) {
684     push @select_fwk, $fwk;
685     $select_fwk{$fwk} = $description;
686 }
687 $curfwk = $frameworkcode;
688 my $framework = CGI::scrolling_list(
689     -name     => 'Frameworks',
690     -id       => 'Frameworks',
691     -default  => $curfwk,
692     -onchange => 'Changefwk(this);',
693     -values   => \@select_fwk,
694     -labels   => \%select_fwk,
695     -size     => 1,
696     -multiple => 0
697 );
698 $template->param( framework => $framework, breedingid => $breedingid );
699
700 # ++ Global
701 $tagslib         = &GetMarcStructure( 1, $frameworkcode );
702 $usedTagsLib     = &GetUsedMarcStructure( $frameworkcode );
703 $mandatory_z3950 = GetMandatoryFieldZ3950($frameworkcode);
704 # -- Global
705
706 my $record   = -1;
707 my $encoding = "";
708 my (
709         $biblionumbertagfield,
710         $biblionumbertagsubfield,
711         $biblioitemnumtagfield,
712         $biblioitemnumtagsubfield,
713         $bibitem,
714         $biblioitemnumber
715 );
716
717 if (($biblionumber) && !($breedingid)){
718         $record = GetMarcBiblio($biblionumber);
719 }
720 if ($breedingid) {
721     ( $record, $encoding ) = MARCfindbreeding( $dbh, $breedingid ) ;
722 }
723
724 $is_a_modif = 0;
725     
726 if ($biblionumber) {
727     $is_a_modif = 1;
728
729     # if it's a modif, retrieve bibli and biblioitem numbers for the future modification of old-DB.
730     ( $biblionumbertagfield, $biblionumbertagsubfield ) =
731         &GetMarcFromKohaField( "biblio.biblionumber", $frameworkcode );
732     ( $biblioitemnumtagfield, $biblioitemnumtagsubfield ) =
733         &GetMarcFromKohaField( "biblioitems.biblioitemnumber", $frameworkcode );
734             
735     # search biblioitems value
736     my $sth =  $dbh->prepare("select biblioitemnumber from biblioitems where biblionumber=?");
737     $sth->execute($biblionumber);
738     ($biblioitemnumber) = $sth->fetchrow;
739 }
740
741 #-------------------------------------------------------------------------------------
742 if ( $op eq "addbiblio" ) {
743 #-------------------------------------------------------------------------------------
744     # getting html input
745     my @params = $input->param();
746     $record = TransformHtmlToMarc( \@params , $input );
747     # check for a duplicate
748     my ($duplicatebiblionumber,$duplicatetitle) = FindDuplicate($record) if (!$is_a_modif);
749     my $confirm_not_duplicate = $input->param('confirm_not_duplicate');
750     # it is not a duplicate (determined either by Koha itself or by user checking it's not a duplicate)
751     if ( !$duplicatebiblionumber or $confirm_not_duplicate ) {
752         my $oldbibnum;
753         my $oldbibitemnum;
754         if (C4::Context->preference("BiblioAddsAuthorities")){
755           my ($countlinked,$countcreated)=BiblioAddAuthorities($record,$frameworkcode);
756         } 
757         if ( $is_a_modif ) {
758             ModBiblioframework( $biblionumber, $frameworkcode ); 
759             ModBiblio( $record, $biblionumber, $frameworkcode );
760         }
761         else {
762             ( $biblionumber, $oldbibitemnum ) = AddBiblio( $record, $frameworkcode );
763         }
764
765         if ($mode ne "popup"){
766             print $input->redirect(
767                 "/cgi-bin/koha/cataloguing/additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode"
768             );
769             exit;
770         } else {
771           $template->param(
772             biblionumber => $biblionumber,
773             done         =>1,
774             popup        =>1
775           );
776           $template->param( title => $record->subfield('200',"a") ) if ($record ne "-1" && C4::Context->preference('marcflavour') =~/unimarc/i);
777           $template->param( title => $record->title() ) if ($record ne "-1" && C4::Context->preference('marcflavour') eq "usmarc");
778           $template->param(
779             popup => $mode,
780             itemtype => $frameworkcode,
781           );
782           output_html_with_http_headers $input, $cookie, $template->output;
783           exit;     
784         }
785     } else {
786     # it may be a duplicate, warn the user and do nothing
787         build_tabs ($template, $record, $dbh,$encoding,$input);
788         $template->param(
789             biblionumber             => $biblionumber,
790             biblioitemnumber         => $biblioitemnumber,
791             duplicatebiblionumber    => $duplicatebiblionumber,
792             duplicatebibid           => $duplicatebiblionumber,
793             duplicatetitle           => $duplicatetitle,
794         );
795     }
796 }
797 elsif ( $op eq "delete" ) {
798     
799     my $error = &DelBiblio($biblionumber);
800     if ($error) {
801         warn "ERROR when DELETING BIBLIO $biblionumber : $error";
802         print "Content-Type: text/html\n\n<html><body><h1>ERROR when DELETING BIBLIO $biblionumber : $error</h1></body></html>";
803         exit;
804     }
805     
806     print $input->redirect('/cgi-bin/koha/catalogue/search.pl');
807     exit;
808     
809 } else {
810    #----------------------------------------------------------------------------
811    # If we're in a duplication case, we have to set to "" the biblionumber
812    # as we'll save the biblio as a new one.
813     if ( $op eq "duplicate" ) {
814         $biblionumber = "";
815     }
816
817 #FIXME: it's kind of silly to go from MARC::Record to MARC::File::XML and then back again just to fix the encoding
818     eval {
819         my $uxml = $record->as_xml;
820         MARC::Record::default_record_format("UNIMARC")
821           if ( C4::Context->preference("marcflavour") eq "UNIMARC" );
822         my $urecord = MARC::Record::new_from_xml( $uxml, 'UTF-8' );
823         $record = $urecord;
824     };
825     build_tabs( $template, $record, $dbh, $encoding,$input );
826     $template->param(
827         biblionumber             => $biblionumber,
828         biblionumbertagfield        => $biblionumbertagfield,
829         biblionumbertagsubfield     => $biblionumbertagsubfield,
830         biblioitemnumtagfield    => $biblioitemnumtagfield,
831         biblioitemnumtagsubfield => $biblioitemnumtagsubfield,
832         biblioitemnumber         => $biblioitemnumber,
833     );
834 }
835
836 $template->param( title => $record->title() ) if ( $record ne "-1" );
837 $template->param(
838     popup => $mode,
839     frameworkcode => $frameworkcode,
840     itemtype => $frameworkcode,
841 );
842
843 output_html_with_http_headers $input, $cookie, $template->output;