adding Algorithm::CheckDigits dependancy, for barcode printing
[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     );
294     if($subfield eq '@'){
295         $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_tag."_".$index_subfield;
296     } else {
297          $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".$index_tag."_".$index_subfield;
298     }
299
300     if(exists $mandatory_z3950->{$tag.$subfield}){
301         $subfield_data{z3950_mandatory} = $mandatory_z3950->{$tag.$subfield};
302     }
303     
304     $subfield_data{visibility} = "display:none;"
305         if (    ($tagslib->{$tag}->{$subfield}->{hidden} % 2 == 1) and $value ne ''
306             or ($value eq '' and !$tagslib->{$tag}->{$subfield}->{mandatory})
307         );
308     
309     # it's an authorised field
310     if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
311         $subfield_data{marc_value} =
312           build_authorized_values_list( $tag, $subfield, $value, $dbh,
313             $authorised_values_sth,$index_tag,$index_subfield );
314
315     # it's a thesaurus / authority field
316     }
317     elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode} ) {
318         $subfield_data{marc_value} =
319                 "<input type=\"text\"
320                         id=\"".$subfield_data{id}."\"
321                         name=\"".$subfield_data{id}."\"
322                         value=\"$value\"
323                         class=\"input_marceditor\"
324                         tabindex=\"1\"                     
325                         disabled=\"disabled\" readonly=\"readonly\" \/>
326                         <span class=\"buttonDot\"
327                                 onclick=\"Dopop('/cgi-bin/koha/authorities/auth_finder.pl?authtypecode=".$tagslib->{$tag}->{$subfield}->{authtypecode}."&index=$subfield_data{id}','$subfield_data{id}')\">...</span>
328                 ";
329     # it's a plugin field
330     }
331     elsif ( $tagslib->{$tag}->{$subfield}->{'value_builder'} ) {
332
333         # opening plugin. Just check wether we are on a developper computer on a production one
334         # (the cgidir differs)
335         my $cgidir = C4::Context->intranetdir . "/cgi-bin/cataloguing/value_builder";
336         unless ( opendir( DIR, "$cgidir" ) ) {
337             $cgidir = C4::Context->intranetdir . "/cataloguing/value_builder";
338         }
339         my $plugin = $cgidir . "/" . $tagslib->{$tag}->{$subfield}->{'value_builder'};
340         do $plugin || die "Plugin Failed: ".$plugin;
341         my $extended_param = plugin_parameters( $dbh, $rec, $tagslib, $subfield_data{id}, $tabloop );
342         my ( $function_name, $javascript ) = plugin_javascript( $dbh, $rec, $tagslib, $subfield_data{id}, $tabloop );
343 #         my ( $function_name, $javascript,$extended_param );
344         
345         $subfield_data{marc_value} =
346                 "<input tabindex=\"1\"
347                         type=\"text\"
348                         id=\"".$subfield_data{id}."\"
349                         name=\"".$subfield_data{id}."\"
350                         value=\"$value\"
351                         class=\"input_marceditor\"
352                         onfocus=\"Focus$function_name($index_tag)\"
353                         onblur=\"Blur$function_name($index_tag); \" \/>
354                 <span class=\"buttonDot\" onclick=\"Clic$function_name('$subfield_data{id}')\">...</a>
355                 $javascript";
356         # it's an hidden field
357     }
358     elsif ( $tag eq '' ) {
359         $subfield_data{marc_value} =
360             "<input tabindex=\"1\"
361                     type=\"hidden\"
362                     id=\"".$subfield_data{id}."\"
363                     name=\"".$subfield_data{id}."\"
364                     value=\"$value\" \/>
365             ";
366     }
367     elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) {
368         $subfield_data{marc_value} =
369             "<input type=\"text\"
370                     id=\"".$subfield_data{id}."\"
371                     name=\"".$subfield_data{id}."\"
372                     class=\"input_marceditor\"
373                     tabindex=\"1\"
374                     value=\"$value\"
375             \/>";
376
377         # it's a standard field
378     }
379     else {
380         if (
381             length($value) > 100
382             or
383             ( C4::Context->preference("marcflavour") eq "UNIMARC" && $tag >= 300
384                 and $tag < 400 && $subfield eq 'a' )
385             or (    $tag >= 500
386                 and $tag < 600
387                 && C4::Context->preference("marcflavour") eq "MARC21" )
388           )
389         {
390             $subfield_data{marc_value} =
391                 "<textarea cols=\"70\"
392                            rows=\"4\"
393                            id=\"".$subfield_data{id}."\"
394                            name=\"".$subfield_data{id}."\"
395                            class=\"input_marceditor\"
396                            tabindex=\"1\"
397                            >$value</textarea>
398                 ";
399         }
400         else {
401             $subfield_data{marc_value} =
402                 "<input type=\"text\"
403                         id=\"".$subfield_data{id}."\"
404                         name=\"".$subfield_data{id}."\"
405                         value=\"$value\"
406                         tabindex=\"1\"
407                         class=\"input_marceditor\"
408                 \/>
409                 ";
410         }
411     }
412     $subfield_data{'index_subfield'} = $index_subfield;
413     return \%subfield_data;
414 }
415
416 sub build_tabs ($$$$$) {
417     my ( $template, $record, $dbh, $encoding,$input ) = @_;
418
419     # fill arrays
420     my @loop_data = ();
421     my $tag;
422
423     my $authorised_values_sth = $dbh->prepare(
424         "select authorised_value,lib
425         from authorised_values
426         where category=? order by lib"
427     );
428     
429     # in this array, we will push all the 10 tabs
430     # to avoid having 10 tabs in the template : they will all be in the same BIG_LOOP
431     my @BIG_LOOP;
432     my %seen;
433     my @tab_data; # all tags to display
434     
435     foreach my $used ( @$usedTagsLib ){
436         push @tab_data,$used->{tagfield} if not $seen{$used->{tagfield}};
437         $seen{$used->{tagfield}}++;
438     }
439         
440     my $max_num_tab=-1;
441     foreach(@$usedTagsLib){
442         if($_->{tab} > -1 && $_->{tab} >= $max_num_tab && $_->{tagfield} != '995'){ # FIXME : MARC21 ?
443             $max_num_tab = $_->{tab}; 
444         }
445     }
446     if($max_num_tab >= 9){
447         $max_num_tab = 9;
448     }
449     # loop through each tab 0 through 9
450     for ( my $tabloop = 0 ; $tabloop <= $max_num_tab ; $tabloop++ ) {
451         my @loop_data = (); #innerloop in the template.
452         my $i = 0;
453         foreach my $tag (@tab_data) {
454             $i++;
455             next if ! $tag;
456             my $indicator;
457             my $index_tag = CreateKey;
458
459             # if MARC::Record is not empty =>use it as master loop, then add missing subfields that should be in the tab.
460             # if MARC::Record is empty => use tab as master loop.
461             if ( $record ne -1 && ( $record->field($tag) || $tag eq '000' ) ) {
462                 my @fields;
463                 if ( $tag ne '000' ) {
464                     @fields = $record->field($tag);
465                 }
466                 else {
467                    push @fields, $record->leader(); # if tag == 000
468                 }
469                 foreach my $field (@fields) {
470                     
471                     my @subfields_data;
472                     if ( $tag < 10 ) {
473                         my ( $value, $subfield );
474                         if ( $tag ne '000' ) {
475                             $value    = $field->data();
476                             $subfield = "@";
477                         }
478                         else {
479                             $value    = $field;
480                             $subfield = '@';
481                         }
482                         next if ( $tagslib->{$tag}->{$subfield}->{tab} ne $tabloop );
483                         next
484                           if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq
485                             'biblio.biblionumber' );
486                         push(
487                             @subfields_data,
488                             &create_input(
489                                 $tag, $subfield, $value, $index_tag, $tabloop, $record,
490                                 $authorised_values_sth,$input
491                             )
492                         );
493                     }
494                     else {
495                         my @subfields = $field->subfields();
496                         foreach my $subfieldcount ( 0 .. $#subfields ) {
497                             my $subfield = $subfields[$subfieldcount][0];
498                             my $value    = $subfields[$subfieldcount][1];
499                             next if ( length $subfield != 1 );
500                             next if ( $tagslib->{$tag}->{$subfield}->{tab} ne $tabloop );
501                             push(
502                                 @subfields_data,
503                                 &create_input(
504                                     $tag, $subfield, $value, $index_tag, $tabloop,
505                                     $record, $authorised_values_sth,$input
506                                 )
507                             );
508                         }
509                     }
510
511                     # now, loop again to add parameter subfield that are not in the MARC::Record
512                     foreach my $subfield ( sort( keys %{ $tagslib->{$tag} } ) )
513                     {
514                         next if ( length $subfield != 1 );
515                         next if ( $tagslib->{$tag}->{$subfield}->{tab} ne $tabloop );
516                         next if ( $tag < 10 );
517                         next
518                           if ( ( $tagslib->{$tag}->{$subfield}->{hidden} <= -4 )
519                             or ( $tagslib->{$tag}->{$subfield}->{hidden} >= 5 )
520                           );    #check for visibility flag
521                         next if ( defined( $field->subfield($subfield) ) );
522                         push(
523                             @subfields_data,
524                             &create_input(
525                                 $tag, $subfield, '', $index_tag, $tabloop, $record,
526                                 $authorised_values_sth,$input
527                             )
528                         );
529                     }
530                     if ( $#subfields_data >= 0 ) {
531                         my %tag_data = (
532                             tag           => $tag,
533                             index         => $index_tag,
534                             tag_lib       => $tagslib->{$tag}->{lib},
535                             subfield_loop => \@subfields_data,
536                             fixedfield    => ($tag < 10)?(1):(0),
537                         );
538                         if ($tag >= 010){ # no indicator for theses tag
539                            $tag_data{indicator} = $field->indicator(1).$field->indicator(2);
540                         }
541                         push( @loop_data, \%tag_data );
542                     }
543                  } # foreach $field end
544
545             # if breeding is empty
546             }
547             else {
548                 my @subfields_data;
549                 foreach my $subfield ( sort( keys %{ $tagslib->{$tag} } ) ) {
550                     next if ( length $subfield != 1 );
551                     next
552                       if ( ( $tagslib->{$tag}->{$subfield}->{hidden} <= -5 )
553                         or ( $tagslib->{$tag}->{$subfield}->{hidden} >= 4 ) )
554                       ;    #check for visibility flag
555                     next
556                       if ( $tagslib->{$tag}->{$subfield}->{tab} ne $tabloop );
557                     push(
558                         @subfields_data,
559                         &create_input(
560                             $tag, $subfield, '', $index_tag, $tabloop, $record,
561                             $authorised_values_sth,$input
562                         )
563                     );
564                 }
565                 if ( $#subfields_data >= 0 ) {
566                     my %tag_data = (
567                         tag              => $tag,
568                         index            => $index_tag,
569                         tag_lib          => $tagslib->{$tag}->{lib},
570                         repeatable       => $tagslib->{$tag}->{repeatable},
571                         indicator        => $indicator,
572                         subfield_loop    => \@subfields_data,
573                         tagfirstsubfield => $subfields_data[0],
574                         fixedfield       => ($tag < 10)?(1):(0)
575                     );
576                     
577                     push @loop_data, \%tag_data ;
578                 }
579             }
580         }
581         if ( $#loop_data >= 0 ) {
582             push @BIG_LOOP, {
583                 number    => $tabloop,
584                 innerloop => \@loop_data,
585             };
586         }
587     }
588     $template->param( BIG_LOOP => \@BIG_LOOP );
589 }
590
591 sub BiblioAddAuthorities{
592   my ( $record, $frameworkcode ) = @_;
593   my $dbh=C4::Context->dbh;
594   my $query=$dbh->prepare(qq|
595 SELECT authtypecode,tagfield
596 FROM marc_subfield_structure 
597 WHERE frameworkcode=? 
598 AND (authtypecode IS NOT NULL AND authtypecode<>\"\")|);
599 # SELECT authtypecode,tagfield
600 # FROM marc_subfield_structure 
601 # WHERE frameworkcode=? 
602 # AND (authtypecode IS NOT NULL OR authtypecode<>\"\")|);
603   $query->execute($frameworkcode);
604   my ($countcreated,$countlinked);
605   while (my $data=$query->fetchrow_hashref){
606     warn Data::Dumper::Dumper($data); 
607     if ($record->field($data->{tagfield})){
608       next if ($record->subfield($data->{tagfield},'3')||$record->subfield($data->{tagfield},'9'));
609       # No authorities id in the tag.
610       # Search if there is any authorities to link to.
611       my $query='at='.$data->{authtypecode}.' ';
612       map {$query.= " and he=".$_->[1] if ($_->[0]=~/[A-z]/)}  $record->field($data->{tagfield})->subfields();
613       warn $query;   
614       my ($error,$results)=SimpleSearch($query,"authorityserver");
615     # there is at least 1 result => return the 1st one
616       if (@$results>1) {
617         my $marcrecord = MARC::File::USMARC::decode($results->[0]);
618         $record->field($data->{tagfield})->add_subfields('9'=>$marcrecord->field('001')->data);
619   $countlinked++;
620       } else {
621   #There are no results, build authority record, add it to Authorities, get authid and add it to 9
622   ###NOTICE : This is only valid if a subfield is linked to one and only one authtypecode
623      
624         my $authtypedata=GetAuthType($data->{authtypecode});
625         my $marcrecordauth=MARC::Record->new();
626         my $field=MARC::Field->new($authtypedata->{auth_tag_to_report},'','',"a"=>"".$record->subfield($data->{tagfield},'a'));
627         map { $field->add_subfields($_->[0]=>$_->[1]) if ($_->[0]=~/[A-z]/ && $_->[0] ne "a" )}  $record->field($data->{tagfield})->subfields();
628         $marcrecordauth->insert_fields_ordered($field);
629         my $authid=AddAuthority($marcrecordauth,'',$data->{authtypecode});
630         $countcreated++;
631         $record->field($data->{tagfield})->add_subfields('9'=>$authid);
632       }
633     }  
634   }
635   return ($countlinked,$countcreated);
636 }
637
638 # ========================
639 #          MAIN
640 #=========================
641 my $input = new CGI;
642 my $error = $input->param('error');
643 my $biblionumber  = $input->param('biblionumber'); # if biblionumber exists, it's a modif, not a new biblio.
644 my $breedingid    = $input->param('breedingid');
645 my $z3950         = $input->param('z3950');
646 my $op            = $input->param('op');
647 my $mode          = $input->param('mode');
648 my $frameworkcode = $input->param('frameworkcode');
649 my $dbh           = C4::Context->dbh;
650
651 $frameworkcode = &GetFrameworkCode($biblionumber)
652   if ( $biblionumber and not($frameworkcode) );
653
654 $frameworkcode = '' if ( $frameworkcode eq 'Default' );
655 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
656     {
657         template_name   => "cataloguing/addbiblio.tmpl",
658         query           => $input,
659         type            => "intranet",
660         authnotrequired => 0,
661         flagsrequired   => { editcatalogue => 1 },
662                 css_page => 'addbiblio.css',
663                 js_page => 'addbiblio.js',
664                 js_libs =>  [   
665                           { lib => 'lib/jquery/jquery.js' },
666                                                   { lib => 'lib/jquery/plugins/jquery.blockUI.js' },
667                         ],
668     }
669 );
670
671 #Getting the list of all frameworks
672 my $queryfwk = $dbh->prepare("select frameworktext, frameworkcode from biblio_framework");
673 $queryfwk->execute;
674 my %select_fwk;
675 my @select_fwk;
676 my $curfwk;
677 push @select_fwk, "Default";
678 $select_fwk{"Default"} = "Default";
679
680 while ( my ( $description, $fwk ) = $queryfwk->fetchrow ) {
681     push @select_fwk, $fwk;
682     $select_fwk{$fwk} = $description;
683 }
684 $curfwk = $frameworkcode;
685 my $framework = CGI::scrolling_list(
686     -name     => 'Frameworks',
687     -id       => 'Frameworks',
688     -default  => $curfwk,
689     -onchange => 'Changefwk(this);',
690     -values   => \@select_fwk,
691     -labels   => \%select_fwk,
692     -size     => 1,
693     -multiple => 0
694 );
695 $template->param( framework => $framework, breedingid => $breedingid );
696
697 # ++ Global
698 $tagslib         = &GetMarcStructure( 1, $frameworkcode );
699 $usedTagsLib     = &GetUsedMarcStructure( $frameworkcode );
700 $mandatory_z3950 = GetMandatoryFieldZ3950($frameworkcode);
701 # -- Global
702
703 my $record   = -1;
704 my $encoding = "";
705 my (
706         $biblionumtagfield,
707         $biblionumtagsubfield,
708         $biblioitemnumtagfield,
709         $biblioitemnumtagsubfield,
710         $bibitem,
711         $biblioitemnumber
712 );
713
714 if (($biblionumber) && !($breedingid)){
715         $record = GetMarcBiblio($biblionumber);
716 }
717 if ($breedingid) {
718     ( $record, $encoding ) = MARCfindbreeding( $dbh, $breedingid ) ;
719 }
720
721 $is_a_modif = 0;
722     
723 if ($biblionumber) {
724     $is_a_modif = 1;
725
726     # if it's a modif, retrieve bibli and biblioitem numbers for the future modification of old-DB.
727     ( $biblionumtagfield, $biblionumtagsubfield ) =
728         &GetMarcFromKohaField( "biblio.biblionumber", $frameworkcode );
729     ( $biblioitemnumtagfield, $biblioitemnumtagsubfield ) =
730         &GetMarcFromKohaField( "biblioitems.biblioitemnumber", $frameworkcode );
731             
732     # search biblioitems value
733     my $sth =  $dbh->prepare("select biblioitemnumber from biblioitems where biblionumber=?");
734     $sth->execute($biblionumber);
735     ($biblioitemnumber) = $sth->fetchrow;
736 }
737
738 #-------------------------------------------------------------------------------------
739 if ( $op eq "addbiblio" ) {
740 #-------------------------------------------------------------------------------------
741     # getting html input
742     my @params = $input->param();
743     $record = TransformHtmlToMarc( \@params , $input );
744     # check for a duplicate
745     my ($duplicatebiblionumber,$duplicatetitle) = FindDuplicate($record) if (!$is_a_modif);
746     my $confirm_not_duplicate = $input->param('confirm_not_duplicate');
747     # it is not a duplicate (determined either by Koha itself or by user checking it's not a duplicate)
748     if ( !$duplicatebiblionumber or $confirm_not_duplicate ) {
749         my $oldbibnum;
750         my $oldbibitemnum;
751         if (C4::Context->preference("BiblioAddsAuthorities")){
752           my ($countlinked,$countcreated)=BiblioAddAuthorities($record,$frameworkcode);
753         } 
754         if ( $is_a_modif ) {
755             ModBiblioframework( $biblionumber, $frameworkcode ); 
756             ModBiblio( $record, $biblionumber, $frameworkcode );
757         }
758         else {
759             ( $biblionumber, $oldbibitemnum ) = AddBiblio( $record, $frameworkcode );
760         }
761
762         if ($mode ne "popup"){
763             print $input->redirect(
764                 "/cgi-bin/koha/cataloguing/additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode"
765             );
766             exit;
767         } else {
768           $template->param(
769             biblionumber => $biblionumber,
770             done         =>1,
771             popup        =>1
772           );
773           $template->param( title => $record->subfield('200',"a") ) if ($record ne "-1" && C4::Context->preference('marcflavour') =~/unimarc/i);
774           $template->param( title => $record->title() ) if ($record ne "-1" && C4::Context->preference('marcflavour') eq "usmarc");
775           $template->param(
776             popup => $mode,
777             itemtype => $frameworkcode,
778           );
779           output_html_with_http_headers $input, $cookie, $template->output;
780           exit;     
781         }
782     } else {
783     # it may be a duplicate, warn the user and do nothing
784         build_tabs ($template, $record, $dbh,$encoding,$input);
785         $template->param(
786             biblionumber             => $biblionumber,
787             biblionumtagfield        => $biblionumtagfield,
788             biblionumtagsubfield     => $biblionumtagsubfield,
789             biblioitemnumtagfield    => $biblioitemnumtagfield,
790             biblioitemnumtagsubfield => $biblioitemnumtagsubfield,
791             biblioitemnumber         => $biblioitemnumber,
792             duplicatebiblionumber    => $duplicatebiblionumber,
793             duplicatebibid           => $duplicatebiblionumber,
794             duplicatetitle           => $duplicatetitle,
795         );
796     }
797 }
798 elsif ( $op eq "delete" ) {
799     
800     my $error = &DelBiblio($biblionumber);
801     if ($error) {
802         warn "ERROR when DELETING BIBLIO $biblionumber : $error";
803         print "Content-Type: text/html\n\n<html><body><h1>ERROR when DELETING BIBLIO $biblionumber : $error</h1></body></html>";
804         exit;
805     }
806     
807     print $input->redirect('/cgi-bin/koha/catalogue/search.pl');
808     exit;
809     
810 } else {
811    #----------------------------------------------------------------------------
812    # If we're in a duplication case, we have to set to "" the biblionumber
813    # as we'll save the biblio as a new one.
814     if ( $op eq "duplicate" ) {
815         $biblionumber = "";
816     }
817
818 #FIXME: it's kind of silly to go from MARC::Record to MARC::File::XML and then back again just to fix the encoding
819     eval {
820         my $uxml = $record->as_xml;
821         MARC::Record::default_record_format("UNIMARC")
822           if ( C4::Context->preference("marcflavour") eq "UNIMARC" );
823         my $urecord = MARC::Record::new_from_xml( $uxml, 'UTF-8' );
824         $record = $urecord;
825     };
826     build_tabs( $template, $record, $dbh, $encoding,$input );
827     $template->param(
828         biblionumber             => $biblionumber,
829         biblionumtagfield        => $biblionumtagfield,
830         biblionumtagsubfield     => $biblionumtagsubfield,
831         biblioitemnumtagfield    => $biblioitemnumtagfield,
832         biblioitemnumtagsubfield => $biblioitemnumtagsubfield,
833         biblioitemnumber         => $biblioitemnumber,
834     );
835 }
836
837 $template->param( title => $record->title() ) if ( $record ne "-1" );
838 $template->param(
839     popup => $mode,
840     frameworkcode => $frameworkcode,
841     itemtype => $frameworkcode,
842 );
843
844 output_html_with_http_headers $input, $cookie, $template->output;