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