Clean up before final commits
[koha.git] / cataloguing / additem.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 CGI;
23 use strict;
24 use C4::Auth;
25 use C4::Output;
26 use C4::Interface::CGI::Output;
27 use C4::Biblio;
28 use C4::Context;
29 use C4::Koha; # XXX subfield_is_koha_internal_p
30 use C4::Search;
31 use C4::Circulation::Circ2;
32 use C4::Log;
33
34 my $logstatus=C4::Context->preference('Activate_log');
35
36 sub find_value {
37         my ($tagfield,$insubfield,$record) = @_;
38         my $result;
39         my $indicator;
40 my $item=$record->{datafield};
41 my $controlfield=$record->{controlfield};
42 my $leader=$record->{leader};
43  if ($tagfield eq '000'){
44 ## We are getting the leader
45 $result=$leader->[0];
46 return($indicator,$result);
47 }
48      if ($tagfield <10){
49         foreach my $control (@$controlfield) {
50                 if ($control->{tag} eq $tagfield){
51                 $result.=$control->{content};
52                 }
53         }
54       }else{
55         foreach my $field (@$item) {            
56               if ($field->{tag} eq $tagfield){  
57                     foreach my $subfield ( $field->{'subfield'}){
58                        foreach my $code ( @$subfield){
59                         if ($code->{code} eq $insubfield) {
60                                 $result .= $code->{content};
61                                 $indicator = $field->{ind1}.$field->{ind2};
62                         }
63                       }## each code
64                   }##each subfield
65               }## if tag
66         }### $field
67      }## tag<10
68         return($indicator,$result);
69 }
70 my $input = new CGI;
71 my $dbh = C4::Context->dbh;
72 my $error = $input->param('error');
73 my $biblionumber = $input->param('biblionumber');
74 my $oldbiblionumber =$biblionumber;
75 my $frameworkcode=$input->param('frameworkcode');
76 my $op = $input->param('op');
77 my $itemnumber = $input->param('itemnumber');
78 my $fromserials=$input->param('fromserials');## if a serial is being added do not display navigation menus
79 my $serialid=$input->param('serialid');
80 my @itemrecords; ##Builds existing items
81 my $bibliorecord; #Bibliorecord relared to this item
82 my $newrecord; ## the new record buing built
83 my $itemrecexist; #item record we are editing
84 my $xml; ## data on html
85  $frameworkcode=MARCfind_frameworkcode($dbh,$biblionumber) unless $frameworkcode;
86 my $tagslib = &MARCitemsgettagslib($dbh,1,$frameworkcode);
87 my $itemrecord;
88 my $nextop="additem";
89 my @errors; # store errors found while checking data BEFORE saving item.
90
91
92 my ($template, $loggedinuser, $cookie)
93     = get_template_and_user({template_name => "cataloguing/additem.tmpl",
94                              query => $input,
95                              type => "intranet",
96                              authnotrequired => 0,
97                              flagsrequired => {editcatalogue => 1},
98                              debug => 1,
99                              });
100
101 #------------------------------------------------------------------------------------------------------------------------------
102 if ($op eq "additem") {
103 #------------------------------------------------------------------------------------------------------------------------------
104         # rebuild
105
106         my @tags = $input->param('tag');
107         my @subfields = $input->param('subfield');
108         my @values = $input->param('field_value');
109         # build indicator hash.
110         my @ind_tag = $input->param('ind_tag');
111         my @indicator = $input->param('indicator');
112         my %indicators;
113         for (my $i=0;$i<=$#ind_tag;$i++) {
114                 $indicators{$ind_tag[$i]} = $indicator[$i];
115         }
116 ## check for malformed xml -- non UTF-8 like (MARC8) will break xml without warning
117 ### This usually happens with data coming from other Z3950 servers
118 ## Slows the saving process so comment out at your own risk
119 eval{
120  $xml = MARChtml2xml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag);        
121 };
122  if ($@){
123 push @errors,"non_utf8" ;
124 $nextop = "additem";
125 goto FINAL;
126   };
127  my $newrecord=XML_xml2hash_onerecord($xml);
128 my $newbarcode=XML_readline_onerecord($newrecord,"barcode","holdings"); 
129
130         # if autoBarcode is ON, calculate barcode...
131         if (C4::Context->preference('autoBarcode')) {   
132                 unless ($newbarcode) {
133                         my $sth_barcode = $dbh->prepare("select max(abs(barcode)) from items");
134                         $sth_barcode->execute;
135                         ($newbarcode) = $sth_barcode->fetchrow;
136                         $newbarcode++;
137                         # OK, we have the new barcode, now create the entry in MARC record
138                         $newrecord=XML_writeline( $newrecord, "barcode", $newbarcode,"holdings" );
139                 }
140         }
141 # check for item barcode # being unique
142         my ($oldrecord)=XMLgetitem($dbh,"",$newbarcode);
143         
144         push @errors,"barcode_not_unique" if($oldrecord);
145 # MARC::Record builded => now, record in DB
146 ## User may be keeping serialids in marc records -- check and add it 
147 if ($fromserials){
148 $newrecord=XML_writeline( $newrecord, "serialid", $serialid,"holdings" );
149 }
150         # if barcode exists, don't create, but report the problem.
151         unless ($oldrecord){
152           $itemnumber=NEWnewitem($dbh,$newrecord,$biblionumber) ;
153                 if ($fromserials){
154                 my $holdingbranch=XML_readline_onerecord($newrecord,"holdingbranch","holdings");        
155                 $template->param(exit=>1,holdingbranch=>$holdingbranch);
156                 }
157         $nextop = "additem";
158         }
159         else{
160                 $nextop = "additem";
161                 $itemrecexist = $newrecord;
162         } 
163 #------------------------------------------------------------------------------------------------------------------------------
164 } elsif ($op eq "edititem") {
165 #------------------------------------------------------------------------------------------------------------------------------
166 # retrieve item if exist => then, it's a modif
167          ($itemrecexist) = XMLgetitemhash($dbh,$itemnumber);## item is already in our array-getit
168         $nextop="saveitem";
169         
170 #logaction($loggedinuser,"acqui.simple","modify",$oldbiblionumber,"item : ".$itemnumber) if ($logstatus);
171         
172 #------------------------------------------------------------------------------------------------------------------------------
173 } elsif ($op eq "delitem") {
174 #------------------------------------------------------------------------------------------------------------------------------
175 # retrieve item if exist => then, it's a modif
176 my $sth=$dbh->prepare("select * from issues i where i.returndate is null and i.itemnumber=?");
177  $sth->execute($itemnumber);
178 my $onloan=$sth->fetchrow;
179 push @errors,"book_on_loan" if ($onloan);
180         if ($onloan){
181         $nextop = "additem";
182 }else{
183         &NEWdelitem($dbh,$itemnumber);
184         $nextop="additem";
185 }
186 #------------------------------------------------------------------------------------------------------------------------------
187 } elsif ($op eq "saveitem") {
188 #------------------------------------------------------------------------------------------------------------------------------
189         # rebuild
190 #warn "save item";
191         my @tags = $input->param('tag');
192         my @subfields = $input->param('subfield');
193         my @values = $input->param('field_value');
194         # build indicator hash.
195         my @ind_tag = $input->param('ind_tag');
196         my @indicator = $input->param('indicator');
197         my $itemnumber = $input->param('itemnumber');
198         my %indicators;
199         for (my $i=0;$i<=$#ind_tag;$i++) {
200                 $indicators{$ind_tag[$i]} = $indicator[$i];
201         }
202 ## check for malformed xml -- non UTF-8 like (MARC8) will break xml without warning
203 ### This usually happens with data coming from other Z3950 servers
204 ## Slows the saving process so comment out at your own risk
205 eval{
206  $xml = MARChtml2xml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag);        
207 };
208          if ($@){
209 push @errors,"non_utf8" ;
210 $nextop = "edititem";
211 goto FINAL;
212   };
213  my $newrecord=XML_xml2hash_onerecord($xml);
214         my $newbarcode=XML_readline_onerecord($newrecord,"barcode","holdings");
215         my ($oldrecord)=XMLgetitem($dbh,"",$newbarcode);
216         $oldrecord=XML_xml2hash_onerecord($oldrecord);
217         my $exist=XML_readline_onerecord($oldrecord,"itemnumber","holdings") if $oldrecord;
218         if ($exist && ($exist ne $itemnumber)){
219         push @errors,"barcode_not_unique" ; ## Although editing user may have changed the barcode
220         $nextop="edititem";
221         }else{
222          NEWmoditem($dbh,$newrecord,$biblionumber,$itemnumber);
223         $itemnumber="";
224         $nextop="additem";
225
226         }
227 }
228
229 #
230 #------------------------------------------------------------------------------------------------------------------------------
231 # build screen with existing items. and "new" one
232 #------------------------------------------------------------------------------------------------------------------------------
233 FINAL:
234 my %indicators;
235 $indicators{995}='  ';
236 # now, build existing item list
237 ###DO NOT CHANGE TO RETRIVE FROM ZEBRA#####
238 my $record =XMLgetbiblio($dbh,$biblionumber);
239 $bibliorecord=XML_xml2hash_onerecord($record);
240 my @itemxmls=XMLgetallitems($dbh,$biblionumber);
241         foreach my $itemrecord(@itemxmls){
242         my $itemhash=XML_xml2hash($itemrecord);
243         push @itemrecords, $itemhash;
244         }
245 ####
246
247
248
249 my ($itemtagfield,$itemtagsubfield) = &MARCfind_marc_from_kohafield("itemnumber","holdings");
250 my @itemnums;
251 my @fields;
252 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
253 my @big_array;
254 my @item_value_loop;
255 my @header_value_loop;
256 unless($fromserials){ ## do not display existing items if adding a serial. It could be a looong list
257 foreach my $itemrecord (@itemrecords){
258
259 my $item=$itemrecord->{datafield};
260 my $controlfield=$itemrecord->{controlfield};
261 my $leader=$itemrecord->{leader};
262 my %this_row;
263         ### The leader
264         unless ($tagslib->{'000'}->{'@'}->{tab}  ne 10 || substr($tagslib->{'000'}->{'@'}->{hidden},1,1)>0){
265         my @datasub='000@';
266         $witness{$datasub[0]} = $tagslib->{'000'}->{'@'}->{lib};
267         $this_row{$datasub[0]} =$leader->[0];
268         }## leader
269         foreach my $control (@$controlfield){
270                 push @itemnums,$control->{content} if ($control->{tag} eq $itemtagfield);
271                 next if ($tagslib->{$control->{tag}}->{'@'}->{tab}  ne 10);
272                 next if (substr($tagslib->{$control->{tag}}->{'@'}->{hidden},1,1)>0);   
273                                         
274                         my @datasub=$control->{tag}.'@';
275                         $witness{$datasub[0]} = $tagslib->{$control->{tag}}->{'@'}->{lib};
276                         $this_row{$datasub[0]} =$control->{content};                    
277         }## Controlfields 
278         foreach my $data (@$item){
279                 foreach my $subfield ( $data->{'subfield'}){
280                         foreach my $code ( @$subfield){ 
281                         # loop through each subfield                    
282                         push @itemnums,$code->{content} if ($data->{tag} eq $itemtagfield && $code->{code} eq $itemtagsubfield);
283                         next if ($tagslib->{$data->{tag}}->{$code->{code}}->{tab}  ne 10);
284                         next if (substr($tagslib->{$data->{tag}}->{$code->{code}}->{hidden},1,1)>0);
285                         $witness{$data->{tag}.$code->{code}} = $tagslib->{$data->{tag}}->{$code->{code}}->{lib};
286                         $this_row{$data->{tag}.$code->{code}} =$code->{content};
287                         }
288                         
289                 }# subfield
290         
291         }## each data
292         if (%this_row) {
293         push(@big_array, \%this_row);
294         }
295 }## each record
296 #fill big_row with missing datas
297 foreach my $subfield_code  (keys(%witness)) {
298         for (my $i=0;$i<=$#big_array;$i++) {
299                 $big_array[$i]{$subfield_code}="&nbsp;" unless ($big_array[$i]{$subfield_code});
300         }
301 }
302 # now, construct template !
303
304 for (my $i=0;$i<=$#big_array; $i++) {
305         my $items_data;
306         foreach my $subfield_code (sort keys(%witness)) {
307                 $items_data .="<td>".$big_array[$i]{$subfield_code}."</td>";
308         }
309         my %row_data;
310         $row_data{item_value} = $items_data;
311         $row_data{itemnumber} = $itemnums[$i];
312         push(@item_value_loop,\%row_data);
313 }
314 foreach my $subfield_code (sort keys(%witness)) {
315         my %header_value;
316         $header_value{header_value} = $witness{$subfield_code};
317         push(@header_value_loop, \%header_value);
318 }
319 }## unless from serials
320 # next item form
321 my @loop_data =();
322 my $i=0;
323 my $authorised_values_sth = $dbh->prepare("select authorised_value,lib from authorised_values where category=? order by lib");
324
325 foreach my $tag (sort keys %{$tagslib}) {
326  if ($itemtagfield <10){
327 next if($tag==$itemtagfield);
328 }
329         my $previous_tag = '';
330 # loop through each subfield
331         foreach my $subfield (sort keys %{$tagslib->{$tag}}) {
332                 next if subfield_is_koha_internal_p($subfield);
333                 next if ($tagslib->{$tag}->{$subfield}->{'tab'}  ne "10");
334                 next if  ($tagslib->{$tag} eq $itemtagfield && $tagslib->{$tag}->{$subfield} eq $itemtagsubfield);
335                 my %subfield_data;
336                 $subfield_data{tag}=$tag;
337                 $subfield_data{subfield}=$subfield;
338                 $subfield_data{marc_lib}="<span id=\"error$i\">".$tagslib->{$tag}->{$subfield}->{lib}."</span>";
339                 $subfield_data{mandatory}=$tagslib->{$tag}->{$subfield}->{mandatory};
340                 $subfield_data{repeatable}=$tagslib->{$tag}->{$subfield}->{repeatable};
341         $subfield_data{hidden}= "display:none" if (substr($tagslib->{$tag}->{$subfield}->{hidden},2,1)>0);
342         
343                 my ($x,$value);
344                 ($x,$value) = find_value($tag,$subfield,$itemrecexist) if ($itemrecexist);
345                 # search for itemcallnumber if applicable
346                 my ($itemcntag,$itemcntagsub)=MARCfind_marc_from_kohafield("itemcallnumber","holdings");
347                 if ($tag eq $itemcntag && $subfield eq $itemcntagsub && C4::Context->preference('itemcallnumber')) {
348                         my $CNtag = substr(C4::Context->preference('itemcallnumber'),0,3);
349                         my $CNsubfield = substr(C4::Context->preference('itemcallnumber'),3,1);
350                         my $CNsubfield2 = substr(C4::Context->preference('itemcallnumber'),4,1);
351                         my $temp1 = XML_readline_onerecord($bibliorecord,"","",$CNtag,$CNsubfield);
352                         my $temp2 = XML_readline_onerecord($bibliorecord,"","",$CNtag,$CNsubfield2);
353                         $value = $temp1.' '.$temp2;
354                         $value=~s/^\s+|\s+$//g;
355                         
356                 }
357                 if ($tagslib->{$tag}->{$subfield}->{authorised_value}) {
358                         my @authorised_values;
359                         my %authorised_lib;
360                         # builds list, depending on authorised value...
361                         #---- branch
362                         if ($tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
363                                 my $sth=$dbh->prepare("select branchcode,branchname from branches order by branchname");
364                                 $sth->execute;
365                                 push @authorised_values, "" unless ($tagslib->{$tag}->{$subfield}->{mandatory});
366                                 while (my ($branchcode,$branchname) = $sth->fetchrow_array) {
367                                         push @authorised_values, $branchcode;
368                                         $authorised_lib{$branchcode}=$branchname;
369                                 }
370                         #----- itemtypes
371                         } elsif ($tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes") {
372                                 my $sth=$dbh->prepare("select itemtype,description from itemtypes order by description");
373                                 $sth->execute;
374                                 push @authorised_values, "" unless ($tagslib->{$tag}->{$subfield}->{mandatory});
375                                 while (my ($itemtype,$description) = $sth->fetchrow_array) {
376                                         push @authorised_values, $itemtype;
377                                         $authorised_lib{$itemtype}=$description;
378                                 }
379                         #---- "true" authorised value
380                         } else {
381                                 $authorised_values_sth->execute($tagslib->{$tag}->{$subfield}->{authorised_value});
382                                 push @authorised_values, "" unless ($tagslib->{$tag}->{$subfield}->{mandatory});
383                                 while (my ($value,$lib) = $authorised_values_sth->fetchrow_array) {
384                                         push @authorised_values, $value;
385                                         $authorised_lib{$value}=$lib;
386                                 }
387                         }
388                         $subfield_data{marc_value}= CGI::scrolling_list(-name=>'field_value',
389                                                                                                                                                 -values=> \@authorised_values,
390                                                                                                                                                 -default=>"$value",                                                                                                                                             -labels => \%authorised_lib,                                                                                                                                            -size=>1,
391                                                                                                                                                 -multiple=>0,                                                                                           );
392                 } elsif ($tagslib->{$tag}->{$subfield}->{thesaurus_category}) {
393                         $subfield_data{marc_value}="<input type=\"text\" name=\"field_value\"  size=47 maxlength=255 DISABLE READONLY> <a href=\"javascript:Dopop('../authorities/auth_finder.pl?authtypecode=".$tagslib->{$tag}->{$subfield}->{authtypecode}."&index=$i',$i)\">...</a>";
394                         #"
395                 } elsif ($tagslib->{$tag}->{$subfield}->{'value_builder'}) {
396                 my $cgidir = C4::Context->intranetdir ."/cgi-bin/value_builder";
397                 unless (opendir(DIR, "$cgidir")) {
398                         $cgidir = C4::Context->intranetdir."/value_builder";
399                 } 
400                 my $plugin=$cgidir."/".$tagslib->{$tag}->{$subfield}->{'value_builder'}; 
401                 require $plugin;
402                 my $extended_param = plugin_parameters($dbh,$newrecord,$tagslib,$i,0);
403                 my ($function_name,$javascript) = plugin_javascript($dbh,$newrecord,$tagslib,$i,0);
404                 $subfield_data{marc_value}="<input type=\"text\" name=\"field_value\"  value=\"$value\" size=\"47\" maxlength=\"255\" DISABLE READONLY OnFocus=\"javascript:Focus$function_name($i)\" OnBlur=\"javascript:Blur$function_name($i)\"> <a href=\"javascript:Clic$function_name($i)\">...</a> $javascript";
405                 } else {
406                         $subfield_data{marc_value}="<input type=\"text\" name=\"field_value\" value=\"$value\" size=50 maxlength=255>";
407                 }
408 #               $subfield_data{marc_value}="<input type=\"text\" name=\"field_value\">";
409                 push(@loop_data, \%subfield_data);
410                 $i++
411         }
412 }
413
414
415 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
416 $template->param(item_loop => \@item_value_loop,
417                                                 item_header_loop => \@header_value_loop,
418                                                 biblionumber =>$biblionumber,
419                                                 title => &XML_readline_onerecord($bibliorecord,"title","biblios"),
420                                                 author => &XML_readline_onerecord($bibliorecord,"author","biblios"),
421                                                 item => \@loop_data,
422                                                 itemnumber => $itemnumber,
423                                                 itemtagfield => $itemtagfield,
424                                                 itemtagsubfield =>$itemtagsubfield,
425                                                 op => $nextop,
426                                                 opisadd => ($nextop eq "saveitem")?0:1,
427                                                 fromserials=>$fromserials, serialid=>$serialid,);
428 foreach my $error (@errors) {
429         $template->param($error => 1);
430
431 }
432 output_html_with_http_headers $input, $cookie, $template->output;
433
434 sub XMLfinditem {
435 my ($itemnumber,@itemrecords)=@_;
436 foreach my $record (@itemrecords){
437 my $inumber=XML_readline_onerecord($record,"itemnumber","holdings");
438         if ($inumber ==$itemnumber){
439         return $record;
440         }
441 }
442 }