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