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