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