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