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