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