Creating Biblio if BiblioAddAuthorities is set in system Preferences.
[koha.git] / cataloguing / addbiblio.pl
1 #!/usr/bin/perl 
2
3 # $Id$
4
5 # Copyright 2000-2002 Katipo Communications
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 with
19 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
20 # Suite 330, Boston, MA  02111-1307 USA
21
22 use strict;
23 use CGI;
24 use C4::Auth;
25 use C4::Output;
26 use C4::Biblio;
27 use C4::Search;
28 use C4::AuthoritiesMarc;
29 use C4::Context;
30 use MARC::Record;
31 use C4::Log;
32 use C4::Koha; # XXX subfield_is_koha_internal_p
33 use Date::Calc qw(Today);
34
35 use MARC::File::USMARC;
36 use MARC::File::XML;
37 if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
38     MARC::File::XML->default_record_format( 'UNIMARC' );
39 }
40
41 use vars qw( $tagslib);
42 use vars qw( $authorised_values_sth);
43 use vars qw( $is_a_modif );
44
45 my $itemtype; # created here because it can be used in build_authorized_values_list sub
46
47 =item find_value
48
49     ($indicators, $value) = find_value($tag, $subfield, $record,$encoding);
50
51 Find the given $subfield in the given $tag in the given
52 MARC::Record $record.  If the subfield is found, returns
53 the (indicators, value) pair; otherwise, (undef, undef) is
54 returned.
55
56 =cut
57
58 sub find_value {
59     my ($tagfield,$insubfield,$record,$encoding) = @_;
60     my @result;
61     my $indicator;
62     if ($tagfield <10) {
63         if ($record->field($tagfield)) {
64             push @result, $record->field($tagfield)->data();
65         } else {
66             push @result,"";
67         }
68     } else {
69         foreach my $field ($record->field($tagfield)) {
70             my @subfields = $field->subfields();
71             foreach my $subfield (@subfields) {
72                 if (@$subfield[0] eq $insubfield) {
73                     push @result,@$subfield[1];
74                     $indicator = $field->indicator(1).$field->indicator(2);
75                 }
76             }
77         }
78     }
79     return($indicator,@result);
80 }
81
82
83 =item MARCfindbreeding
84
85     $record = MARCfindbreeding($dbh, $breedingid);
86
87 Look up the breeding farm with database handle $dbh, for the
88 record with id $breedingid.  If found, returns the decoded
89 MARC::Record; otherwise, -1 is returned (FIXME).
90 Returns as second parameter the character encoding.
91
92 =cut
93
94 sub MARCfindbreeding {
95     my ($dbh,$id) = @_;
96     my $sth = $dbh->prepare("select file,marc,encoding from marc_breeding where id=?");
97     $sth->execute($id);
98     my ($file,$marc,$encoding) = $sth->fetchrow;
99     if ($marc) {
100         my $record = MARC::Record->new_from_usmarc($marc);
101         if ($record->field('010')){ 
102             foreach my $field ($record->field('010'))
103             {
104                 foreach my $subfield ($field->subfield('a')){
105                     my $newisbn = $field->subfield('a');
106                     $newisbn =~ s/-//g;
107                     $field->update( 'a' => $newisbn );
108                 }
109     #                   $record->insert_fields_ordered($record->field('010'));
110             }           
111         }
112         if ($record->subfield(100,'a')) {
113             my $f100a=$record->subfield(100,'a');
114             my $f100 = $record->field(100);
115             my $f100temp = $f100->as_string;
116             $record->delete_field($f100);
117             if (length($f100temp)>28) {
118                 substr($f100temp,26,2,"50");
119                 $f100->update('a' => $f100temp);
120                 my $f100 = MARC::Field->new('100','','','a' => $f100temp);
121                 $record->insert_fields_ordered($f100);
122             }
123         }
124         if (ref($record) eq undef) {
125             return -1;
126         } else {
127             if (C4::Context->preference("z3950NormalizeAuthor") and C4::Context->preference("z3950AuthorAuthFields")){
128                 my ($tag,$subfield) = GetMarcFromKohaField("biblio.author");
129 #                 my $summary = C4::Context->preference("z3950authortemplate");
130                 my $auth_fields = C4::Context->preference("z3950AuthorAuthFields");
131                 my @auth_fields= split /,/,$auth_fields;
132                 my $field;
133                 #warn $record->as_formatted;
134                 if ($record->field($tag)){
135                     foreach my $tmpfield ($record->field($tag)->subfields){
136 #                        foreach my $subfieldcode ($tmpfield->subfields){
137                         my $subfieldcode=shift @$tmpfield;
138                         my $subfieldvalue=shift @$tmpfield;
139                         if ($field){
140                             $field->add_subfields("$subfieldcode"=>$subfieldvalue) if ($subfieldcode ne $subfield);
141                         } else {
142                             $field=MARC::Field->new($tag,"","",$subfieldcode=>$subfieldvalue) if ($subfieldcode ne $subfield);
143                         }
144                     }
145 #                    warn $field->as_formatted;
146 #                    }
147                 }
148                 $record->delete_field($record->field($tag));
149                 foreach my $fieldtag (@auth_fields){
150                     next unless ($record->field($fieldtag));
151                     my $lastname = $record->field($fieldtag)->subfield('a');
152                     my $firstname= $record->field($fieldtag)->subfield('b');
153                     my $title = $record->field($fieldtag)->subfield('c');
154                     my $number= $record->field($fieldtag)->subfield('d');
155                     if ($title){
156 #                         $field->add_subfields("$subfield"=>"[ ".ucfirst($title).ucfirst($firstname)." ".$number." ]");
157                         $field->add_subfields("$subfield"=>ucfirst($title)." ".ucfirst($firstname)." ".$number);
158                     }else{
159 #                         $field->add_subfields("$subfield"=>"[ ".ucfirst($firstname).", ".ucfirst($lastname)." ]");
160                         $field->add_subfields("$subfield"=>ucfirst($firstname).", ".ucfirst($lastname));
161                     }
162                 }
163                 $record->insert_fields_ordered($field);
164             }
165             return $record,$encoding;
166         }
167     }
168     return -1;
169 }
170
171
172 =item build_authorized_values_list
173
174 =cut
175
176 sub build_authorized_values_list ($$$$$) {
177     my($tag, $subfield, $value, $dbh,$authorised_values_sth) = @_;
178
179     my @authorised_values;
180     my %authorised_lib;
181
182     # builds list, depending on authorised value...
183
184     #---- branch
185     if ($tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
186     my $sth=$dbh->prepare("select branchcode,branchname from branches order by branchname");
187     $sth->execute;
188     push @authorised_values, ""
189         unless ($tagslib->{$tag}->{$subfield}->{mandatory});
190
191     while (my ($branchcode,$branchname) = $sth->fetchrow_array) {
192         push @authorised_values, $branchcode;
193         $authorised_lib{$branchcode}=$branchname;
194     }
195
196     #----- itemtypes
197     } elsif ($tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes") {
198         my $sth=$dbh->prepare("select itemtype,description from itemtypes order by description");
199         $sth->execute;
200         push @authorised_values, "" unless ($tagslib->{$tag}->{$subfield}->{mandatory});
201     
202         while (my ($itemtype,$description) = $sth->fetchrow_array) {
203             push @authorised_values, $itemtype;
204             $authorised_lib{$itemtype}=$description;
205         }
206         $value=$itemtype unless ($value);
207
208     #---- "true" authorised value
209     } else {
210         $authorised_values_sth->execute($tagslib->{$tag}->{$subfield}->{authorised_value});
211
212         push @authorised_values, "" unless ($tagslib->{$tag}->{$subfield}->{mandatory});
213     
214         while (my ($value,$lib) = $authorised_values_sth->fetchrow_array) {
215             push @authorised_values, $value;
216             $authorised_lib{$value}=$lib;
217         }
218     }
219     return CGI::scrolling_list( -name     => 'field_value',
220                 -values   => \@authorised_values,
221                 -default  => $value,
222                 -labels   => \%authorised_lib,
223                 -override => 1,
224                 -size     => 1,
225                 -multiple => 0 );
226 }
227
228 =item create_input
229
230  builds the <input ...> entry for a subfield.
231
232 =cut
233
234 sub create_input () {
235     my ($tag,$subfield,$value,$i,$tabloop,$rec,$authorised_values_sth) = @_;
236     # must be encoded as utf-8 before it reaches the editor
237         #use Encode;
238         #$value = encode('utf-8', $value);
239     $value =~ s/"/&quot;/g;
240     # if there is no value provided but a default value in parameters, get it 
241     unless ($value) {
242         $value = $tagslib->{$tag}->{$subfield}->{defaultvalue};
243         # get today date & replace YYYY, MM, DD if provided in the default value
244         my ($year,$month,$day) = Today();
245         $month = sprintf("%02d",$month);
246         $day = sprintf("%02d",$day);
247         $value =~ s/YYYY/$year/g;
248         $value =~ s/MM/$month/g;
249         $value =~ s/DD/$day/g;
250         
251     }
252     my $dbh = C4::Context->dbh;
253     my %subfield_data;
254     $subfield_data{tag}=$tag;
255     $subfield_data{subfield}=$subfield;
256     $subfield_data{marc_lib}="<span id=\"error$i\" title=\"".$tagslib->{$tag}->{$subfield}->{lib}."\">".substr($tagslib->{$tag}->{$subfield}->{lib},0,15)."</span>";
257     $subfield_data{marc_lib_plain}=$tagslib->{$tag}->{$subfield}->{lib};
258     $subfield_data{tag_mandatory}=$tagslib->{$tag}->{mandatory};
259     $subfield_data{mandatory}=$tagslib->{$tag}->{$subfield}->{mandatory};
260     $subfield_data{repeatable}=$tagslib->{$tag}->{$subfield}->{repeatable};
261     $subfield_data{kohafield}=$tagslib->{$tag}->{$subfield}->{kohafield};
262     $subfield_data{index} = $i;
263     $subfield_data{visibility} = "display:none" unless (($tagslib->{$tag}->{$subfield}->{hidden}%2==0) or $value ne ''); #check parity
264     # it's an authorised field
265     if ($tagslib->{$tag}->{$subfield}->{authorised_value}) {
266         $subfield_data{marc_value}= build_authorized_values_list($tag, $subfield, $value, $dbh,$authorised_values_sth);
267     # it's a thesaurus / authority field
268     } elsif ($tagslib->{$tag}->{$subfield}->{authtypecode}) {
269         $subfield_data{marc_value}="<input type=\"text\" onblur=\"this.style.backgroundColor='#ffffff';\" onfocus=\"this.style.backgroundColor='#ffff00;'\"\" tabindex=\"1\" type=\"text\" name=\"field_value\" value=\"$value\" size=\"70\" maxlength=\"255\"> <a  style=\"cursor: help;\" href=\"javascript:Dopop('../authorities/auth_finder.pl?authtypecode=".$tagslib->{$tag}->{$subfield}->{authtypecode}."&index=$i',$i)\">...</a>";
270     # it's a plugin field
271     } elsif ($tagslib->{$tag}->{$subfield}->{'value_builder'}) {
272         # opening plugin. Just check wether we are on a developper computer on a production one
273         # (the cgidir differs)
274         my $cgidir = C4::Context->intranetdir ."/cgi-bin/cataloguing/value_builder";
275         unless (opendir(DIR, "$cgidir")) {
276             $cgidir = C4::Context->intranetdir."/cataloguing/value_builder";
277         }
278         my $plugin=$cgidir."/".$tagslib->{$tag}->{$subfield}->{'value_builder'};
279         do $plugin;
280         my $extended_param = plugin_parameters($dbh,$rec,$tagslib,$i,$tabloop);
281         my ($function_name,$javascript) = plugin_javascript($dbh,$rec,$tagslib,$i,$tabloop);
282         $subfield_data{marc_value}="<input tabindex=\"1\" type=\"text\" name=\"field_value\"  value=\"$value\" size=\"70\" maxlength=\"255\" OnFocus=\"javascript:Focus$function_name($i)\" OnBlur=\"javascript:Blur$function_name($i); \"> <a  style=\"cursor: help;\" href=\"javascript:Clic$function_name($i)\">...</a> $javascript";
283     # it's an hidden field
284     } elsif  ($tag eq '') {
285          $subfield_data{marc_value}="<input onblur=\"this.style.backgroundColor='#ffffff';\" onfocus=\"this.style.backgroundColor='#ffff00'; \" tabindex=\"1\" type=\"hidden\" name=\"field_value\" value=\"$value\">";
286     } elsif  ($tagslib->{$tag}->{$subfield}->{'hidden'}) {
287         $subfield_data{marc_value}="<input onblur=\"this.style.backgroundColor='#ffffff';\" onfocus=\"this.style.backgroundColor='#ffff00'; \" tabindex=\"1\" type=\"text\" name=\"field_value\" value=\"$value\" size=\"70\" maxlength=\"255\" >";
288     # it's a standard field
289     } else {
290         if (length($value) >100 or (C4::Context->preference("marcflavour") eq "UNIMARC" && $tag >=300 and $tag <400 && $subfield eq 'a') or ($tag >=500 and $tag <600 && C4::Context->preference("marcflavour") eq "MARC21")) {
291             $subfield_data{marc_value}="<textarea tabindex=\"1\" name=\"field_value\" cols=\"70\" rows=\"5\" >$value</textarea>";
292         } else {
293             $subfield_data{marc_value}="<input onblur=\"this.style.backgroundColor='#ffffff';\" onfocus=\"this.style.backgroundColor='#ffff00'; \" tabindex=\"1\" type=\"text\" name=\"field_value\" value=\"$value\" size=\"70\">"; #"
294         }
295     }
296     return \%subfield_data;
297 }
298
299 sub build_tabs ($$$$) {
300     my($template, $record, $dbh,$encoding) = @_;
301     # fill arrays
302     my @loop_data =();
303     my $tag;
304     my $i=0;
305     my $authorised_values_sth = $dbh->prepare("select authorised_value,lib
306         from authorised_values
307         where category=? order by lib");
308     
309     # in this array, we will push all the 10 tabs
310     # to avoid having 10 tabs in the template : they will all be in the same BIG_LOOP
311     my @BIG_LOOP;
312
313 # loop through each tab 0 through 9
314     for (my $tabloop = 0; $tabloop <= 9; $tabloop++) {
315         my @loop_data = ();
316         foreach my $tag (sort(keys (%{$tagslib}))) {
317             my $indicator;
318     # if MARC::Record is not empty => use it as master loop, then add missing subfields that should be in the tab.
319     # if MARC::Record is empty => use tab as master loop.
320             if ($record ne -1 && ($record->field($tag) || $tag eq '000')) {
321                 my @fields;
322                 if ($tag ne '000') {
323                     @fields = $record->field($tag);
324                 } else {
325                     push @fields,$record->leader();
326                 }
327                 foreach my $field (@fields)  {
328                     my @subfields_data;
329                     if ($tag<10) {
330                         my ($value,$subfield);
331                         if ($tag ne '000') {
332                             $value=$field->data();
333                             $subfield="@";
334                         } else {
335                             $value = $field;
336                             $subfield='@';
337                         }
338                         next if ($tagslib->{$tag}->{$subfield}->{tab} ne $tabloop);
339                         next if ($tagslib->{$tag}->{$subfield}->{kohafield} eq 'biblio.biblionumber');
340                         push(@subfields_data, &create_input($tag,$subfield,$value,$i,$tabloop,$record,$authorised_values_sth));
341                         $i++;
342                     } else {
343                         my @subfields=$field->subfields();
344                         foreach my $subfieldcount (0..$#subfields) {
345                             my $subfield=$subfields[$subfieldcount][0];
346                             my $value=$subfields[$subfieldcount][1];
347                             next if (length $subfield !=1);
348                             next if ($tagslib->{$tag}->{$subfield}->{tab} ne $tabloop);
349                             push(@subfields_data, &create_input($tag,$subfield,$value,$i,$tabloop,$record,$authorised_values_sth));
350                             $i++;
351                         }
352                     }
353 # now, loop again to add parameter subfield that are not in the MARC::Record
354                     foreach my $subfield (sort( keys %{$tagslib->{$tag}})) {
355                         next if (length $subfield !=1);
356                         next if ($tagslib->{$tag}->{$subfield}->{tab} ne $tabloop);
357                         next if ($tag<10);
358                         next if (($tagslib->{$tag}->{$subfield}->{hidden}<=-4) or ($tagslib->{$tag}->{$subfield}->{hidden}>=5) ); #check for visibility flag
359                         next if (defined($field->subfield($subfield)));
360                         push(@subfields_data, &create_input($tag,$subfield,'',$i,$tabloop,$record,$authorised_values_sth));
361                         $i++;
362                     }
363                     if ($#subfields_data >= 0) {
364                         my %tag_data;
365                         $tag_data{tag} = $tag;
366                         $tag_data{tag_lib} = $tagslib->{$tag}->{lib};
367                         $tag_data{repeatable} = $tagslib->{$tag}->{repeatable};
368                         $tag_data{indicator} = $record->field($tag)->indicator(1). $record->field($tag)->indicator(2) if ($tag>=10);
369                         $tag_data{subfield_loop} = \@subfields_data;
370                         if ($tag<10) {
371                                                     $tag_data{fixedfield} = 1;
372                                             }
373
374                         push (@loop_data, \%tag_data);
375                     }
376 # If there is more than 1 field, add an empty hidden field as separator.
377                     if ($#fields >=1 && $#loop_data >=0 && $loop_data[$#loop_data]->{'tag'} eq $tag) {
378                         my @subfields_data;
379                         my %tag_data;
380                         push(@subfields_data, &create_input('','','',$i,$tabloop,$record,$authorised_values_sth));
381                         $tag_data{tag} = '';
382                         $tag_data{tag_lib} = '';
383                         $tag_data{indicator} = '';
384                         $tag_data{subfield_loop} = \@subfields_data;
385                         if ($tag<10) {
386                                                        $tag_data{fixedfield} = 1;
387                                     }
388                         push (@loop_data, \%tag_data);
389                         $i++;
390                     }
391                 }
392     # if breeding is empty
393             } else {
394                 my @subfields_data;
395                 foreach my $subfield (sort(keys %{$tagslib->{$tag}})) {
396                     next if (length $subfield !=1);
397                     next if (($tagslib->{$tag}->{$subfield}->{hidden}<=-5) or ($tagslib->{$tag}->{$subfield}->{hidden}>=4) ); #check for visibility flag
398                     next if ($tagslib->{$tag}->{$subfield}->{tab} ne $tabloop);
399                     push(@subfields_data, &create_input($tag,$subfield,'',$i,$tabloop,$record,$authorised_values_sth));
400                     $i++;
401                 }
402                 if ($#subfields_data >= 0) {
403                     my %tag_data;
404                     $tag_data{tag} = $tag;
405                     $tag_data{tag_lib} = $tagslib->{$tag}->{lib};
406                     $tag_data{repeatable} = $tagslib->{$tag}->{repeatable};
407                     $tag_data{indicator} = $indicator;
408                     $tag_data{subfield_loop} = \@subfields_data;
409                     $tag_data{tagfirstsubfield} = $tag_data{subfield_loop}[0];
410                     if ($tag<10) {
411                         $tag_data{fixedfield} = 1;
412                     }
413                     push (@loop_data, \%tag_data);
414                 }
415             }
416         }
417         if ($#loop_data >=0) {
418             my %big_loop_line;
419             $big_loop_line{number}=$tabloop;
420             $big_loop_line{innerloop}=\@loop_data;
421             push @BIG_LOOP,\%big_loop_line;
422         }
423 #         $template->param($tabloop."XX" =>\@loop_data);
424     }
425     $template->param(BIG_LOOP => \@BIG_LOOP);
426 }
427
428
429
430 sub build_hidden_data () {
431     # build hidden data =>
432     # we store everything, even if we show only requested subfields.
433
434     my @loop_data =();
435     my $i=0;
436     foreach my $tag (keys %{$tagslib}) {
437     my $previous_tag = '';
438
439     # loop through each subfield
440     foreach my $subfield (keys %{$tagslib->{$tag}}) {
441         next if ($subfield eq 'lib');
442         next if ($subfield eq 'tab');
443         next if ($subfield eq 'mandatory');
444         next if ($subfield eq 'repeatable');
445         next if ($tagslib->{$tag}->{$subfield}->{'tab'}  ne "-1");
446         my %subfield_data;
447         $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
448         $subfield_data{marc_mandatory}=$tagslib->{$tag}->{$subfield}->{mandatory};
449         $subfield_data{marc_repeatable}=$tagslib->{$tag}->{$subfield}->{repeatable};
450         $subfield_data{marc_value}="<input type=\"hidden\" name=\"field_value[]\">";
451         push(@loop_data, \%subfield_data);
452         $i++
453     }
454     }
455 }
456
457
458 sub BiblioAddAuthorities{
459   my ( $record, $frameworkcode ) = @_;
460   my $dbh=C4::Context->dbh;
461   my $query=$dbh->prepare(qq|
462 SELECT authtypecode,tagfield
463 FROM marc_subfield_structure 
464 WHERE frameworkcode=? 
465 AND (authtypecode IS NOT NULL AND authtypecode<>\"\")|);
466 # SELECT authtypecode,tagfield
467 # FROM marc_subfield_structure 
468 # WHERE frameworkcode=? 
469 # AND (authtypecode IS NOT NULL OR authtypecode<>\"\")|);
470   $query->execute($frameworkcode);
471   my ($countcreated,$countlinked);
472   while (my $data=$query->fetchrow_hashref){
473     if ($record->field($data->{tagfield})){
474       next if ($record->subfield($data->{tagfield},'3')||$record->subfield($data->{tagfield},'9'));
475       # No authorities id in the tag.
476       # Search if there is any authorities to link to.
477       my $query='at='.$data->{authtypecode}.' ';
478       map {$query.= " and he=\"".$_->[1]."\"" if ($_->[0]=~/[A-z]/)}  $record->field($data->{tagfield})->subfields();
479       warn $query;   
480       my ($error,$results)=SimpleSearch($query,"authorityserver");
481     # there is at least 1 result => return the 1st one
482       if (@$results>1) {
483         my $marcrecord = MARC::File::USMARC::decode($results->[0]);
484         $record->field($data->{tagfield})->add_subfields('9'=>$marcrecord->field('001')->data);
485   $countlinked++;
486       } else {
487   #There are no results, build authority record, add it to Authorities, get authid and add it to 9
488   ###NOTICE : This is only valid if a subfield is linked to one and only one authtypecode
489
490       
491         my $authtypedata=GetAuthType($data->{authtypecode});
492         my $marcrecordauth=MARC::Record->new();
493         my $field=MARC::Field->new($authtypedata->{auth_tag_to_report},'','',"a"=>"".$record->subfield($data->{tagfield},'a'));
494         map { $field->add_subfields($_->[0]=>$_->[1]) if ($_->[0]=~/[A-z]/ && $_->[0] ne "a" )}  $record->field($data->{tagfield})->subfields();
495         $marcrecordauth->insert_fields_ordered($field);
496         my $authid=AddAuthority($record,'',$data->{authtypecode});
497         $countcreated++;
498         $record->field($data->{tagfield})->add_subfields('9'=>$authid);
499       }
500     }  
501   }
502   return ($countlinked,$countcreated);
503 }
504
505 # ======================== 
506 #          MAIN 
507 #=========================
508 my $input = new CGI;
509 my $error = $input->param('error');
510 my $biblionumber=$input->param('biblionumber'); # if biblionumber exists, it's a modif, not a new biblio.
511 my $breedingid = $input->param('breedingid');
512 my $z3950 = $input->param('z3950');
513 my $op = $input->param('op');
514 my $mode = $input->param('mode');
515 my $frameworkcode = $input->param('frameworkcode');
516 my $dbh = C4::Context->dbh;
517
518 $frameworkcode = &GetFrameworkCode($biblionumber) if ($biblionumber and not ($frameworkcode));
519
520 $frameworkcode='' if ($frameworkcode eq 'Default');
521 my ($template, $loggedinuser, $cookie)
522     = get_template_and_user({template_name => "cataloguing/addbiblio.tmpl",
523                  query => $input,
524                  type => "intranet",
525                  authnotrequired => 0,
526                  flagsrequired => {editcatalogue => 1},
527                  debug => 1,
528                  });
529
530 #Getting the list of all frameworks
531 my $queryfwk =$dbh->prepare("select frameworktext, frameworkcode from biblio_framework");
532 $queryfwk->execute;
533 my %select_fwk;
534 my @select_fwk;
535 my $curfwk;
536 push @select_fwk,"Default";
537 $select_fwk{"Default"} = "Default";
538 while (my ($description, $fwk) =$queryfwk->fetchrow) {
539     push @select_fwk, $fwk;
540     $select_fwk{$fwk} = $description;
541 }
542 $curfwk=$frameworkcode;
543 my $framework=CGI::scrolling_list( 
544             -name     => 'Frameworks',
545             -id => 'Frameworks',
546             -default => $curfwk,
547             -OnChange => 'Changefwk(this);',
548             -values   => \@select_fwk,
549             -labels   => \%select_fwk,
550             -size     => 1,
551             -multiple => 0 );
552 $template->param( framework => $framework, breedingid => $breedingid);
553
554 $tagslib = &GetMarcStructure(1,$frameworkcode);
555 my $record=-1;
556 my $encoding="";
557 $record = GetMarcBiblio( $biblionumber ) if ($biblionumber);
558 ($record,$encoding) = MARCfindbreeding($dbh,$breedingid) if ($breedingid);
559
560 # warn "biblionumber : $biblionumber = ".$record->as_formatted;
561 $is_a_modif=0;
562 my ($biblionumtagfield,$biblionumtagsubfield);
563 my ($biblioitemnumtagfield,$biblioitemnumtagsubfield,$bibitem,$biblioitemnumber);
564 if ($biblionumber) {
565     $is_a_modif=1;
566     # if it's a modif, retrieve bibli and biblioitem numbers for the future modification of old-DB.
567     ($biblionumtagfield,$biblionumtagsubfield) = &GetMarcFromKohaField("biblio.biblionumber",$frameworkcode);
568     ($biblioitemnumtagfield,$biblioitemnumtagsubfield) = &GetMarcFromKohaField("biblioitems.biblioitemnumber",$frameworkcode);
569     # search biblioitems value
570     my $sth=$dbh->prepare("select biblioitemnumber from biblioitems where biblionumber=?");
571     $sth->execute($biblionumber);
572     ($biblioitemnumber) = $sth->fetchrow;
573 }
574 #-------------------------------------------------------------------------------------
575 if ($op eq "addbiblio") {
576 #-------------------------------------------------------------------------------------
577     # rebuild
578     my @tags = $input->param('tag');
579     my @subfields = $input->param('subfield');
580     my @values = $input->param('field_value');
581     # build indicator hash.
582     my @ind_tag = $input->param('ind_tag');
583     my @indicator = $input->param('indicator');
584     if (C4::Context->preference('TemplateEncoding') eq "iso-8859-1") {
585         $record = TransformHtmlToMarc($dbh,\@tags,\@subfields,\@values,\@indicator,\@ind_tag);
586     } else {
587         my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag);
588         $record=MARC::Record->new_from_xml($xml,C4::Context->preference('TemplateEncoding'),C4::Context->preference('marcflavour'));
589 #         warn "MARC :".$record->as_formatted;
590 #         die;
591     }
592     # check for a duplicate
593     my ($duplicatebiblionumber,$duplicatetitle) = FindDuplicate($record) if (!$is_a_modif);
594     my $confirm_not_duplicate = $input->param('confirm_not_duplicate');
595     # it is not a duplicate (determined either by Koha itself or by user checking it's not a duplicate)
596     if (!$duplicatebiblionumber or $confirm_not_duplicate) {
597         # MARC::Record built => now, record in DB
598         my $oldbibnum;
599         my $oldbibitemnum;
600         if ($is_a_modif) {
601             ModBiblioframework($biblionumber,$frameworkcode);
602             ModBiblio($record,$biblionumber,$frameworkcode);
603         }
604         else {
605             ($biblionumber,$oldbibitemnum) = AddBiblio($record,$frameworkcode);
606         }
607         if (C4::Context->preference("BiblioAddsAuthorities")){
608           my ($countlinked,$countcreated)=BiblioAddAuthorities($record,$frameworkcode);
609         }
610     
611     # now, redirect to additem page
612         if ($mode ne "popup"){
613         print $input->redirect("/cgi-bin/koha/cataloguing/additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode");
614         exit;
615         } else {
616           $template->param(
617             biblionumber => $biblionumber,
618             done         =>1,
619             popup        =>1
620           );
621           $template->param( title => $record->subfield('200',"a") ) if ($record ne "-1" && C4::Context->preference('marcflavour') =~/unimarc/i);
622           $template->param( title => $record->title() ) if ($record ne "-1" && C4::Context->preference('marcflavour') eq "usmarc");
623           $template->param(
624                   popup => $mode,
625                   itemtype => $frameworkcode, # HINT: if the library has itemtype = framework, itemtype is auto filled !
626                   );
627           output_html_with_http_headers $input, $cookie, $template->output;
628           exit;     
629         }        
630     } else {
631     # it may be a duplicate, warn the user and do nothing
632         build_tabs ($template, $record, $dbh,$encoding);
633         build_hidden_data;
634         $template->param(
635             biblionumber             => $biblionumber,
636             biblionumtagfield        => $biblionumtagfield,
637             biblionumtagsubfield     => $biblionumtagsubfield,
638             biblioitemnumtagfield    => $biblioitemnumtagfield,
639             biblioitemnumtagsubfield => $biblioitemnumtagsubfield,
640             biblioitemnumber         => $biblioitemnumber,
641             duplicatebiblionumber    => $duplicatebiblionumber,
642             duplicatebibid           => $duplicatebiblionumber,
643             duplicatetitle           => $duplicatetitle,
644         );
645     }
646 #--------------------------------------------------------------------------
647 } elsif ($op eq "addfield") {
648 #--------------------------------------------------------------------------
649     my $addedfield = $input->param('addfield_field');
650     my $cntrepeatfield=$input->param('repeat_field');
651     $cntrepeatfield=1 unless ($cntrepeatfield);
652     my $tagaddfield_subfield = $input->param('addfield_subfield');
653     my @tags = $input->param('tag');
654     my @subfields = $input->param('subfield');
655     my @values = $input->param('field_value');
656     # build indicator hash.
657     my @ind_tag = $input->param('ind_tag');
658     my @indicator = $input->param('indicator');
659     my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag);
660     my $record;
661     if (C4::Context->preference('TemplateEncoding') eq "iso-8859-1") {
662         my %indicators;
663         for (my $i=0;$i<=$#ind_tag;$i++) {
664             $indicators{$ind_tag[$i]} = $indicator[$i];
665         }
666         $record = TransformHtmlToMarc($dbh,\@tags,\@subfields,\@values,%indicators);
667     } else {
668         my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag);
669         $record=MARC::Record->new_from_xml($xml,C4::Context->preference('TemplateEncoding'),C4::Context->preference('marcflavour'));
670     }
671     for (my $i=1;$i<=$cntrepeatfield;$i++){
672         my $field = MARC::Field->new("$addedfield",'','',"$tagaddfield_subfield" => "");
673         $record->append_fields($field);
674     }
675     #warn "result : ".$record->as_formatted;
676     build_tabs ($template, $record, $dbh,$encoding);
677     build_hidden_data;
678     $template->param(
679         biblionumber             => $biblionumber,
680         biblionumtagfield        => $biblionumtagfield,
681         biblionumtagsubfield     => $biblionumtagsubfield,
682         biblioitemnumtagfield    => $biblioitemnumtagfield,
683         biblioitemnumtagsubfield => $biblioitemnumtagsubfield,
684         biblioitemnumber         => $biblioitemnumber );
685 } elsif ($op eq "delete") {
686 #-----------------------------------------------------------------------------
687     my $error = &DelBiblio($biblionumber);
688     if ($error) {
689         warn "ERROR when DELETING BIBLIO $biblionumber : $error";
690         print "Content-Type: text/html\n\n<html><body><h1>ERROR when DELETING BIBLIO $biblionumber : $error</h1></body></html>";
691     } else {
692     print "Content-Type: text/html\n\n<META HTTP-EQUIV=Refresh CONTENT=\"0; URL=/cgi-bin/koha/catalogue/search.pl?type=intranet\"></html>";
693     }
694     exit;
695 #----------------------------------------------------------------------------
696 } else {
697 #----------------------------------------------------------------------------
698     # If we're in a duplication case, we have to set to "" the biblionumber
699     # as we'll save the biblio as a new one.
700     if ($op eq "duplicate")
701     {
702         $biblionumber= "";
703     }
704     #FIXME: it's kind of silly to go from MARC::Record to MARC::File::XML and then back again just to fix the encoding
705     eval {
706         my $uxml = $record->as_xml;
707         MARC::Record::default_record_format("UNIMARC") if (C4::Context->preference("marcflavour") eq "UNIMARC");
708         my $urecord = MARC::Record::new_from_xml($uxml, 'UTF-8');
709         $record = $urecord;
710     };
711     build_tabs ($template, $record, $dbh,$encoding);
712     build_hidden_data;
713     $template->param(
714         biblionumber             => $biblionumber,
715         biblionumtagfield        => $biblionumtagfield,
716         biblionumtagsubfield     => $biblionumtagsubfield,
717         biblioitemnumtagfield    => $biblioitemnumtagfield,
718         biblioitemnumtagsubfield => $biblioitemnumtagsubfield,
719         biblioitemnumber         => $biblioitemnumber,
720         );
721 }
722 $template->param( title => $record->title() ) if ($record ne "-1");
723 $template->param(
724         popup => $mode,
725         frameworkcode => $frameworkcode,
726         itemtype => $frameworkcode, # HINT: if the library has itemtype = framework, itemtype is auto filled !
727         hide_marc => C4::Context->preference('hide_marc'),
728         intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
729         intranetstylesheet => C4::Context->preference("intranetstylesheet"),
730         IntranetNav => C4::Context->preference("IntranetNav"),
731         advancedMARCEditor => C4::Context->preference("advancedMARCEditor"),
732         );
733 output_html_with_http_headers $input, $cookie, $template->output;