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