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