bug 2254 [1/3]: fixed GetAuthType(); avoid crash
[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
36 use Date::Calc qw(Today);
37 use MARC::File::USMARC;
38 use MARC::File::XML;
39
40 if ( C4::Context->preference('marcflavour') eq 'UNIMARC' ) {
41     MARC::File::XML->default_record_format('UNIMARC');
42 }
43
44 our($tagslib,$authorised_values_sth,$is_a_modif,$usedTagsLib,$mandatory_z3950);
45
46 =item MARCfindbreeding
47
48     $record = MARCfindbreeding($breedingid);
49
50 Look up the import record repository for the record with
51 record with id $breedingid.  If found, returns the decoded
52 MARC::Record; otherwise, -1 is returned (FIXME).
53 Returns as second parameter the character encoding.
54
55 =cut
56
57 sub MARCfindbreeding {
58     my ( $id ) = @_;
59     my ($marc, $encoding) = GetImportRecordMarc($id);
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           #---- class_sources
198     }
199     elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
200         push @authorised_values, ""
201           unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
202
203         my $class_sources = GetClassSources();
204
205         my $default_source = C4::Context->preference("DefaultClassificationSource");
206
207         foreach my $class_source (sort keys %$class_sources) {
208             next unless $class_sources->{$class_source}->{'used'} or
209                         ($value and $class_source eq $value) or
210                         ($class_source eq $default_source);
211             push @authorised_values, $class_source;
212             $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
213             $value = $class_source unless ($value);
214             $value = $default_source unless ($value);
215         }
216         #---- "true" authorised value
217     }
218     else {
219         $authorised_values_sth->execute(
220             $tagslib->{$tag}->{$subfield}->{authorised_value} );
221
222         push @authorised_values, ""
223           unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
224
225         while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
226             push @authorised_values, $value;
227             $authorised_lib{$value} = $lib;
228         }
229     }
230     return CGI::scrolling_list(
231         -name     => "tag_".$tag."_subfield_".$subfield."_".$index_tag."_".$index_subfield,
232         -values   => \@authorised_values,
233         -default  => $value,
234         -labels   => \%authorised_lib,
235         -override => 1,
236         -size     => 1,
237         -multiple => 0,
238         -tabindex => 1,
239         -id       => "tag_".$tag."_subfield_".$subfield."_".$index_tag."_".$index_subfield,
240         -class    => "input_marceditor",
241     );
242 }
243
244 =item CreateKey
245
246     Create a random value to set it into the input name
247
248 =cut
249
250 sub CreateKey(){
251     return int(rand(1000000));
252 }
253
254 =item GetMandatoryFieldZ3950
255
256     This function return an hashref which containts all mandatory field
257     to search with z3950 server.
258     
259 =cut
260
261 sub GetMandatoryFieldZ3950($){
262     my $frameworkcode = shift;
263     my @isbn   = GetMarcFromKohaField('biblioitems.isbn',$frameworkcode);
264     my @title  = GetMarcFromKohaField('biblio.title',$frameworkcode);
265     my @author = GetMarcFromKohaField('biblio.author',$frameworkcode);
266     my @issn   = GetMarcFromKohaField('biblioitems.issn',$frameworkcode);
267     my @lccn   = GetMarcFromKohaField('biblioitems.lccn',$frameworkcode);
268     
269     return {
270         $isbn[0].$isbn[1]     => 'isbn',
271         $title[0].$title[1]   => 'title',
272         $author[0].$author[1] => 'author',
273         $issn[0].$issn[1]     => 'issn',
274         $lccn[0].$lccn[1]     => 'lccn',
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
305     # map '@' as "subfield" label for fixed fields
306     # to something that's allowed in a div id.
307     my $id_subfield = $subfield;
308     $id_subfield = "00" if $id_subfield eq "@";
309
310     my %subfield_data = (
311         tag        => $tag,
312         subfield   => $id_subfield,
313         marc_lib   => substr( $tagslib->{$tag}->{$subfield}->{lib}, 0, 22 ),
314         marc_lib_plain => $tagslib->{$tag}->{$subfield}->{lib}, 
315         tag_mandatory  => $tagslib->{$tag}->{mandatory},
316         mandatory      => $tagslib->{$tag}->{$subfield}->{mandatory},
317         repeatable     => $tagslib->{$tag}->{$subfield}->{repeatable},
318         kohafield      => $tagslib->{$tag}->{$subfield}->{kohafield},
319         index          => $index_tag,
320         id             => "tag_".$tag."_subfield_".$id_subfield."_".$index_tag."_".$index_subfield,
321         value          => $value,
322         random         => CreateKey(),
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 subfield $9 linking to an authority record - see bug 2206
343     }
344     elsif ($subfield eq "9" and
345            exists($tagslib->{$tag}->{'a'}->{authtypecode}) and
346            defined($tagslib->{$tag}->{'a'}->{authtypecode}) and
347            $tagslib->{$tag}->{'a'}->{authtypecode} ne '') {
348
349         $subfield_data{marc_value} =
350             "<input type=\"text\"
351                     id=\"".$subfield_data{id}."\"
352                     name=\"".$subfield_data{id}."\"
353                     value=\"$value\"
354                     class=\"input_marceditor\"
355                     tabindex=\"1\"
356                     size=\"5\"
357                     maxlength=\"255\" 
358                     readonly=\"readonly\"
359                     \/>";
360
361     # it's a thesaurus / authority field
362     }
363     elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode} ) {
364      if (C4::Context->preference("BiblioAddsAuthorities")) {
365         $subfield_data{marc_value} =
366             "<input type=\"text\"
367                     id=\"".$subfield_data{id}."\"
368                     name=\"".$subfield_data{id}."\"
369                     value=\"$value\"
370                     class=\"input_marceditor\"
371                     tabindex=\"1\"
372                     size=\"67\"
373                     maxlength=\"255\" 
374                     \/>
375                     <a href=\"#\" class=\"buttonDot\"
376                         onclick=\"Dopop('/cgi-bin/koha/authorities/auth_finder.pl?authtypecode=".$tagslib->{$tag}->{$subfield}->{authtypecode}."&amp;index=$subfield_data{id}','$subfield_data{id}'); return false;\" title=\"Tag Editor\">...</a>
377             ";
378       } else {
379         $subfield_data{marc_value} =
380             "<input type=\"text\"
381                     id=\"".$subfield_data{id}."\"
382                     name=\"".$subfield_data{id}."\"
383                     value=\"$value\"
384                     class=\"input_marceditor\"
385                     tabindex=\"1\"
386                     size=\"67\"
387                     maxlength=\"255\" 
388                     readonly=\"readonly\"
389                     \/>
390                     <a href=\"#\" class=\"buttonDot\"
391                         onclick=\"Dopop('/cgi-bin/koha/authorities/auth_finder.pl?authtypecode=".$tagslib->{$tag}->{$subfield}->{authtypecode}."&amp;index=$subfield_data{id}','$subfield_data{id}'); return false;\" title=\"Tag Editor\">...</a>
392             ";
393       }
394     # it's a plugin field
395     }
396     elsif ( $tagslib->{$tag}->{$subfield}->{'value_builder'} ) {
397
398         # opening plugin. Just check wether we are on a developper computer on a production one
399         # (the cgidir differs)
400         my $cgidir = C4::Context->intranetdir . "/cgi-bin/cataloguing/value_builder";
401         unless ( opendir( DIR, "$cgidir" ) ) {
402             $cgidir = C4::Context->intranetdir . "/cataloguing/value_builder";
403             closedir( DIR );
404         }
405         my $plugin = $cgidir . "/" . $tagslib->{$tag}->{$subfield}->{'value_builder'};
406         if (do $plugin) {
407             my $extended_param = plugin_parameters( $dbh, $rec, $tagslib, $subfield_data{id}, $tabloop );
408             my ( $function_name, $javascript ) = plugin_javascript( $dbh, $rec, $tagslib, $subfield_data{id}, $tabloop );
409         
410             $subfield_data{marc_value} =
411                     "<input tabindex=\"1\"
412                             type=\"text\"
413                             id=\"".$subfield_data{id}."\"
414                             name=\"".$subfield_data{id}."\"
415                             value=\"$value\"
416                             class=\"input_marceditor\"
417                             onfocus=\"Focus$function_name($index_tag)\"
418                             size=\"67\"
419                             maxlength=\"255\" 
420                             onblur=\"Blur$function_name($index_tag); \" \/>
421                             <a href=\"#\" class=\"buttonDot\" onclick=\"Clic$function_name('$subfield_data{id}'); return false;\" title=\"Tag Editor\">...</a>
422                     $javascript";
423         } else {
424             warn "Plugin Failed: $plugin";
425             # supply default input form
426             $subfield_data{marc_value} =
427                 "<input type=\"text\"
428                         id=\"".$subfield_data{id}."\"
429                         name=\"".$subfield_data{id}."\"
430                         value=\"$value\"
431                         tabindex=\"1\"
432                         size=\"67\"
433                         maxlength=\"255\" 
434                         class=\"input_marceditor\"
435                 \/>
436                 ";
437         }
438         # it's an hidden field
439     }
440     elsif ( $tag eq '' ) {
441         $subfield_data{marc_value} =
442             "<input tabindex=\"1\"
443                     type=\"hidden\"
444                     id=\"".$subfield_data{id}."\"
445                     name=\"".$subfield_data{id}."\"
446                     size=\"67\"
447                     maxlength=\"255\" 
448                     value=\"$value\" \/>
449             ";
450     }
451     elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) {
452         $subfield_data{marc_value} =
453             "<input type=\"text\"
454                     id=\"".$subfield_data{id}."\"
455                     name=\"".$subfield_data{id}."\"
456                     class=\"input_marceditor\"
457                     tabindex=\"1\"
458                     size=\"67\"
459                     maxlength=\"255\" 
460                     value=\"$value\"
461             \/>";
462
463         # it's a standard field
464     }
465     else {
466         if (
467             length($value) > 100
468             or
469             ( C4::Context->preference("marcflavour") eq "UNIMARC" && $tag >= 300
470                 and $tag < 400 && $subfield eq 'a' )
471             or (    $tag >= 500
472                 and $tag < 600
473                 && C4::Context->preference("marcflavour") eq "MARC21" )
474           )
475         {
476             $subfield_data{marc_value} =
477                 "<textarea cols=\"70\"
478                            rows=\"4\"
479                            id=\"".$subfield_data{id}."\"
480                            name=\"".$subfield_data{id}."\"
481                            class=\"input_marceditor\"
482                            tabindex=\"1\"
483                            >$value</textarea>
484                 ";
485         }
486         else {
487             $subfield_data{marc_value} =
488                 "<input type=\"text\"
489                         id=\"".$subfield_data{id}."\"
490                         name=\"".$subfield_data{id}."\"
491                         value=\"$value\"
492                         tabindex=\"1\"
493                         size=\"67\"
494                         maxlength=\"255\" 
495                         class=\"input_marceditor\"
496                 \/>
497                 ";
498         }
499     }
500     $subfield_data{'index_subfield'} = $index_subfield;
501     return \%subfield_data;
502 }
503
504
505 =item format_indicator
506
507 Translate indicator value for output form - specifically, map
508 indicator = ' ' to ''.  This is for the convenience of a cataloger
509 using a mouse to select an indicator input.
510
511 =cut
512
513 sub format_indicator {
514     my $ind_value = shift;
515     return '' if not defined $ind_value;
516     return '' if $ind_value eq ' ';
517     return $ind_value;
518 }
519
520 sub build_tabs ($$$$$) {
521     my ( $template, $record, $dbh, $encoding,$input ) = @_;
522
523     # fill arrays
524     my @loop_data = ();
525     my $tag;
526
527     my $authorised_values_sth = $dbh->prepare(
528         "select authorised_value,lib
529         from authorised_values
530         where category=? order by lib"
531     );
532     
533     # in this array, we will push all the 10 tabs
534     # to avoid having 10 tabs in the template : they will all be in the same BIG_LOOP
535     my @BIG_LOOP;
536     my %seen;
537     my @tab_data; # all tags to display
538     
539     foreach my $used ( @$usedTagsLib ){
540         push @tab_data,$used->{tagfield} if not $seen{$used->{tagfield}};
541         $seen{$used->{tagfield}}++;
542     }
543         
544     my $max_num_tab=-1;
545     foreach(@$usedTagsLib){
546         if($_->{tab} > -1 && $_->{tab} >= $max_num_tab && $_->{tagfield} != '995'){ # FIXME : MARC21 ?
547             $max_num_tab = $_->{tab}; 
548         }
549     }
550     if($max_num_tab >= 9){
551         $max_num_tab = 9;
552     }
553     # loop through each tab 0 through 9
554     for ( my $tabloop = 0 ; $tabloop <= $max_num_tab ; $tabloop++ ) {
555         my @loop_data = (); #innerloop in the template.
556         my $i = 0;
557         foreach my $tag (@tab_data) {
558             $i++;
559             next if ! $tag;
560             my ($indicator1, $indicator2);
561             my $index_tag = CreateKey;
562
563             # if MARC::Record is not empty =>use it as master loop, then add missing subfields that should be in the tab.
564             # if MARC::Record is empty => use tab as master loop.
565             if ( $record ne -1 && ( $record->field($tag) || $tag eq '000' ) ) {
566                 my @fields;
567                 if ( $tag ne '000' ) {
568                     @fields = $record->field($tag);
569                 }
570                 else {
571                    push @fields, $record->leader(); # if tag == 000
572                 }
573                 # loop through each field
574                 foreach my $field (@fields) {
575                     
576                     my @subfields_data;
577                     if ( $tag < 10 ) {
578                         my ( $value, $subfield );
579                         if ( $tag ne '000' ) {
580                             $value    = $field->data();
581                             $subfield = "@";
582                         }
583                         else {
584                             $value    = $field;
585                             $subfield = '@';
586                         }
587                         next if ( $tagslib->{$tag}->{$subfield}->{tab} ne $tabloop );
588                         next
589                           if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq
590                             'biblio.biblionumber' );
591                         push(
592                             @subfields_data,
593                             &create_input(
594                                 $tag, $subfield, $value, $index_tag, $tabloop, $record,
595                                 $authorised_values_sth,$input
596                             )
597                         );
598                     }
599                     else {
600                         my @subfields = $field->subfields();
601                         foreach my $subfieldcount ( 0 .. $#subfields ) {
602                             my $subfield = $subfields[$subfieldcount][0];
603                             my $value    = $subfields[$subfieldcount][1];
604                             next if ( length $subfield != 1 );
605                             next if ( $tagslib->{$tag}->{$subfield}->{tab} ne $tabloop );
606                             push(
607                                 @subfields_data,
608                                 &create_input(
609                                     $tag, $subfield, $value, $index_tag, $tabloop,
610                                     $record, $authorised_values_sth,$input
611                                 )
612                             );
613                         }
614                     }
615
616                     # now, loop again to add parameter subfield that are not in the MARC::Record
617                     foreach my $subfield ( sort( keys %{ $tagslib->{$tag} } ) )
618                     {
619                         next if ( length $subfield != 1 );
620                         next if ( $tagslib->{$tag}->{$subfield}->{tab} ne $tabloop );
621                         next if ( $tag < 10 );
622                         next
623                           if ( ( $tagslib->{$tag}->{$subfield}->{hidden} <= -4 )
624                             or ( $tagslib->{$tag}->{$subfield}->{hidden} >= 5 ) )
625                             and not ( $subfield eq "9" and
626                                       exists($tagslib->{$tag}->{'a'}->{authtypecode}) and
627                                       defined($tagslib->{$tag}->{'a'}->{authtypecode}) and
628                                       $tagslib->{$tag}->{'a'}->{authtypecode} ne ""
629                                     )
630                           ;    #check for visibility flag
631                                # if subfield is $9 in a field whose $a is authority-controlled,
632                                # always include in the form regardless of the hidden setting - bug 2206
633                         next if ( defined( $field->subfield($subfield) ) );
634                         push(
635                             @subfields_data,
636                             &create_input(
637                                 $tag, $subfield, '', $index_tag, $tabloop, $record,
638                                 $authorised_values_sth,$input
639                             )
640                         );
641                     }
642                     if ( $#subfields_data >= 0 ) {
643                         # build the tag entry.
644                         # note that the random() field is mandatory. Otherwise, on repeated fields, you'll 
645                         # have twice the same "name" value, and cgi->param() will return only one, making
646                         # all subfields to be merged in a single field.
647                         my %tag_data = (
648                             tag           => $tag,
649                             index         => $index_tag,
650                             tag_lib       => $tagslib->{$tag}->{lib},
651                             repeatable       => $tagslib->{$tag}->{repeatable},
652                             subfield_loop => \@subfields_data,
653                             fixedfield    => $tag < 10?1:0,
654                             random        => CreateKey,
655                         );
656                         if ($tag >= 010){ # no indicator for theses tag
657                            $tag_data{indicator1} = format_indicator($field->indicator(1)),
658                            $tag_data{indicator2} = format_indicator($field->indicator(2)),
659                         }
660                         push( @loop_data, \%tag_data );
661                     }
662                  } # foreach $field end
663
664             # if breeding is empty
665             }
666             else {
667                 my @subfields_data;
668                 foreach my $subfield ( sort( keys %{ $tagslib->{$tag} } ) ) {
669                     next if ( length $subfield != 1 );
670                     next
671                       if ( ( $tagslib->{$tag}->{$subfield}->{hidden} <= -5 )
672                         or ( $tagslib->{$tag}->{$subfield}->{hidden} >= 4 ) )
673                       and not ( $subfield eq "9" and
674                                 exists($tagslib->{$tag}->{'a'}->{authtypecode}) and
675                                 defined($tagslib->{$tag}->{'a'}->{authtypecode}) and
676                                 $tagslib->{$tag}->{'a'}->{authtypecode} ne ""
677                               )
678                       ;    #check for visibility flag
679                            # if subfield is $9 in a field whose $a is authority-controlled,
680                            # always include in the form regardless of the hidden setting - bug 2206
681                     next
682                       if ( $tagslib->{$tag}->{$subfield}->{tab} ne $tabloop );
683                     push(
684                         @subfields_data,
685                         &create_input(
686                             $tag, $subfield, '', $index_tag, $tabloop, $record,
687                             $authorised_values_sth,$input
688                         )
689                     );
690                 }
691                 if ( $#subfields_data >= 0 ) {
692                     my %tag_data = (
693                         tag              => $tag,
694                         index            => $index_tag,
695                         tag_lib          => $tagslib->{$tag}->{lib},
696                         repeatable       => $tagslib->{$tag}->{repeatable},
697                         indicator1       => $indicator1,
698                         indicator2       => $indicator2,
699                         subfield_loop    => \@subfields_data,
700                         tagfirstsubfield => $subfields_data[0],
701                         fixedfield       => $tag < 10?1:0,
702                     );
703                     
704                     push @loop_data, \%tag_data ;
705                 }
706             }
707         }
708         if ( $#loop_data >= 0 ) {
709             push @BIG_LOOP, {
710                 number    => $tabloop,
711                 innerloop => \@loop_data,
712             };
713         }
714     }
715     $template->param( BIG_LOOP => \@BIG_LOOP );
716 }
717
718 #
719 # sub that tries to find authorities linked to the biblio
720 # the sub :
721 #   - search in the authority DB for the same authid (in $9 of the biblio)
722 #   - search in the authority DB for the same 001 (in $3 of the biblio in UNIMARC)
723 #   - search in the authority DB for the same values (exactly) (in all subfields of the biblio)
724 # if the authority is found, the biblio is modified accordingly to be connected to the authority.
725 # if the authority is not found, it's added, and the biblio is then modified to be connected to the authority.
726 #
727
728 sub BiblioAddAuthorities{
729   my ( $record, $frameworkcode ) = @_;
730   my $dbh=C4::Context->dbh;
731   my $query=$dbh->prepare(qq|
732 SELECT authtypecode,tagfield
733 FROM marc_subfield_structure 
734 WHERE frameworkcode=? 
735 AND (authtypecode IS NOT NULL AND authtypecode<>\"\")|);
736 # SELECT authtypecode,tagfield
737 # FROM marc_subfield_structure 
738 # WHERE frameworkcode=? 
739 # AND (authtypecode IS NOT NULL OR authtypecode<>\"\")|);
740   $query->execute($frameworkcode);
741   my ($countcreated,$countlinked);
742   while (my $data=$query->fetchrow_hashref){
743     foreach my $field ($record->field($data->{tagfield})){
744       next if ($field->subfield('3')||$field->subfield('9'));
745       # No authorities id in the tag.
746       # Search if there is any authorities to link to.
747       my $query='at='.$data->{authtypecode}.' ';
748       map {$query.= ' and he,ext="'.$_->[1].'"' if ($_->[0]=~/[A-z]/)}  $field->subfields();
749       my ($error, $results, $total_hits)=SimpleSearch( $query, undef, undef, [ "authorityserver" ] );
750     # there is only 1 result 
751           if ( $error ) {
752         warn "BIBLIOADDSAUTHORITIES: $error";
753             return (0,0) ;
754           }
755       if ($results && scalar(@$results)==1) {
756         my $marcrecord = MARC::File::USMARC::decode($results->[0]);
757         $field->add_subfields('9'=>$marcrecord->field('001')->data);
758         $countlinked++;
759       } elsif (scalar(@$results)>1) {
760    #More than One result 
761    #This can comes out of a lack of a subfield.
762 #         my $marcrecord = MARC::File::USMARC::decode($results->[0]);
763 #         $record->field($data->{tagfield})->add_subfields('9'=>$marcrecord->field('001')->data);
764   $countlinked++;
765       } else {
766   #There are no results, build authority record, add it to Authorities, get authid and add it to 9
767   ###NOTICE : This is only valid if a subfield is linked to one and only one authtypecode     
768   ###NOTICE : This can be a problem. We should also look into other types and rejected forms.
769          my $authtypedata=GetAuthType($data->{authtypecode});
770          next unless $authtypedata;
771          my $marcrecordauth=MARC::Record->new();
772          my $authfield=MARC::Field->new($authtypedata->{auth_tag_to_report},'','',"a"=>"".$field->subfield('a'));
773          map { $authfield->add_subfields($_->[0]=>$_->[1]) if ($_->[0]=~/[A-z]/ && $_->[0] ne "a" )}  $field->subfields();
774          $marcrecordauth->insert_fields_ordered($authfield);
775 #          warn "AUTH RECORD ADDED : ".$marcrecordauth->as_formatted;
776          my $authid=AddAuthority($marcrecordauth,'',$data->{authtypecode});
777          $countcreated++;
778          $field->add_subfields('9'=>$authid);
779       }
780     }  
781   }
782   return ($countlinked,$countcreated);
783 }
784
785 # ========================
786 #          MAIN
787 #=========================
788 my $input = new CGI;
789 my $error = $input->param('error');
790 my $biblionumber  = $input->param('biblionumber'); # if biblionumber exists, it's a modif, not a new biblio.
791 my $breedingid    = $input->param('breedingid');
792 my $z3950         = $input->param('z3950');
793 my $op            = $input->param('op');
794 my $mode          = $input->param('mode');
795 my $frameworkcode = $input->param('frameworkcode');
796 my $dbh           = C4::Context->dbh;
797
798 $frameworkcode = &GetFrameworkCode($biblionumber)
799   if ( $biblionumber and not($frameworkcode) );
800
801 $frameworkcode = '' if ( $frameworkcode eq 'Default' );
802 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
803     {
804         template_name   => "cataloguing/addbiblio.tmpl",
805         query           => $input,
806         type            => "intranet",
807         authnotrequired => 0,
808         flagsrequired   => { editcatalogue => 1 },
809     }
810 );
811
812 # Getting the list of all frameworks
813 # get framework list
814 my $frameworks = getframeworks;
815 my @frameworkcodeloop;
816 foreach my $thisframeworkcode ( keys %$frameworks ) {
817         my %row = (
818                 value         => $thisframeworkcode,
819                 frameworktext => $frameworks->{$thisframeworkcode}->{'frameworktext'},
820         );
821         if ($frameworkcode eq $thisframeworkcode){
822                 $row{'selected'}="selected=\"selected\"";
823                 }
824         push @frameworkcodeloop, \%row;
825
826 $template->param( frameworkcodeloop => \@frameworkcodeloop,
827         breedingid => $breedingid );
828
829 # ++ Global
830 $tagslib         = &GetMarcStructure( 1, $frameworkcode );
831 $usedTagsLib     = &GetUsedMarcStructure( $frameworkcode );
832 $mandatory_z3950 = GetMandatoryFieldZ3950($frameworkcode);
833 # -- Global
834
835 my $record   = -1;
836 my $encoding = "";
837 my (
838         $biblionumbertagfield,
839         $biblionumbertagsubfield,
840         $biblioitemnumtagfield,
841         $biblioitemnumtagsubfield,
842         $bibitem,
843         $biblioitemnumber
844 );
845
846 if (($biblionumber) && !($breedingid)){
847         $record = GetMarcBiblio($biblionumber);
848 }
849 if ($breedingid) {
850     ( $record, $encoding ) = MARCfindbreeding( $breedingid ) ;
851 }
852
853 $is_a_modif = 0;
854     
855 if ($biblionumber) {
856     $is_a_modif = 1;
857         $template->param( title => $record->title(), );
858
859     # if it's a modif, retrieve bibli and biblioitem numbers for the future modification of old-DB.
860     ( $biblionumbertagfield, $biblionumbertagsubfield ) =
861         &GetMarcFromKohaField( "biblio.biblionumber", $frameworkcode );
862     ( $biblioitemnumtagfield, $biblioitemnumtagsubfield ) =
863         &GetMarcFromKohaField( "biblioitems.biblioitemnumber", $frameworkcode );
864             
865     # search biblioitems value
866     my $sth =  $dbh->prepare("select biblioitemnumber from biblioitems where biblionumber=?");
867     $sth->execute($biblionumber);
868     ($biblioitemnumber) = $sth->fetchrow;
869 }
870
871 #-------------------------------------------------------------------------------------
872 if ( $op eq "addbiblio" ) {
873 #-------------------------------------------------------------------------------------
874     # getting html input
875     my @params = $input->param();
876     $record = TransformHtmlToMarc( \@params , $input );
877     # check for a duplicate
878     my ($duplicatebiblionumber,$duplicatetitle) = FindDuplicate($record) if (!$is_a_modif);
879     my $confirm_not_duplicate = $input->param('confirm_not_duplicate');
880     # it is not a duplicate (determined either by Koha itself or by user checking it's not a duplicate)
881     if ( !$duplicatebiblionumber or $confirm_not_duplicate ) {
882         my $oldbibnum;
883         my $oldbibitemnum;
884         if (C4::Context->preference("BiblioAddsAuthorities")){
885           my ($countlinked,$countcreated)=BiblioAddAuthorities($record,$frameworkcode);
886         } 
887         if ( $is_a_modif ) {
888             ModBiblioframework( $biblionumber, $frameworkcode ); 
889             ModBiblio( $record, $biblionumber, $frameworkcode );
890         }
891         else {
892             ( $biblionumber, $oldbibitemnum ) = AddBiblio( $record, $frameworkcode );
893         }
894
895         if ($mode ne "popup"){
896             print $input->redirect(
897                 "/cgi-bin/koha/cataloguing/additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode"
898             );
899             exit;
900         } else {
901           $template->param(
902             biblionumber => $biblionumber,
903             done         =>1,
904             popup        =>1
905           );
906           $template->param( title => $record->subfield('200',"a") ) if ($record ne "-1" && C4::Context->preference('marcflavour') =~/unimarc/i);
907           $template->param( title => $record->title() ) if ($record ne "-1" && C4::Context->preference('marcflavour') eq "usmarc");
908           $template->param(
909             popup => $mode,
910             itemtype => $frameworkcode,
911           );
912           output_html_with_http_headers $input, $cookie, $template->output;
913           exit;     
914         }
915     } else {
916     # it may be a duplicate, warn the user and do nothing
917         build_tabs ($template, $record, $dbh,$encoding,$input);
918         $template->param(
919             biblionumber             => $biblionumber,
920             biblioitemnumber         => $biblioitemnumber,
921             duplicatebiblionumber    => $duplicatebiblionumber,
922             duplicatebibid           => $duplicatebiblionumber,
923             duplicatetitle           => $duplicatetitle,
924         );
925     }
926 }
927 elsif ( $op eq "delete" ) {
928     
929     my $error = &DelBiblio($biblionumber);
930     if ($error) {
931         warn "ERROR when DELETING BIBLIO $biblionumber : $error";
932         print "Content-Type: text/html\n\n<html><body><h1>ERROR when DELETING BIBLIO $biblionumber : $error</h1></body></html>";
933         exit;
934     }
935     
936     print $input->redirect('/cgi-bin/koha/catalogue/search.pl');
937     exit;
938     
939 } else {
940    #----------------------------------------------------------------------------
941    # If we're in a duplication case, we have to set to "" the biblionumber
942    # as we'll save the biblio as a new one.
943     if ( $op eq "duplicate" ) {
944         $biblionumber = "";
945     }
946
947 #FIXME: it's kind of silly to go from MARC::Record to MARC::File::XML and then back again just to fix the encoding
948     eval {
949         my $uxml = $record->as_xml;
950         MARC::Record::default_record_format("UNIMARC")
951           if ( C4::Context->preference("marcflavour") eq "UNIMARC" );
952         my $urecord = MARC::Record::new_from_xml( $uxml, 'UTF-8' );
953         $record = $urecord;
954     };
955     build_tabs( $template, $record, $dbh, $encoding,$input );
956     $template->param(
957         biblionumber             => $biblionumber,
958         biblionumbertagfield        => $biblionumbertagfield,
959         biblionumbertagsubfield     => $biblionumbertagsubfield,
960         biblioitemnumtagfield    => $biblioitemnumtagfield,
961         biblioitemnumtagsubfield => $biblioitemnumtagsubfield,
962         biblioitemnumber         => $biblioitemnumber,
963     );
964 }
965
966 $template->param( title => $record->title() ) if ( $record ne "-1" );
967 $template->param(
968     popup => $mode,
969     frameworkcode => $frameworkcode,
970     itemtype => $frameworkcode,
971 );
972
973 output_html_with_http_headers $input, $cookie, $template->output;