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