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