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