bugfix (security flaw) : the additem template was open AFTER doing actions
[koha.git] / cataloguing / additem.pl
1 #!/usr/bin/perl
2
3
4 # Copyright 2000-2002 Katipo Communications
5 #
6 # This file is part of Koha.
7 #
8 # Koha is free software; you can redistribute it and/or modify it under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 2 of the License, or (at your option) any later
11 # version.
12 #
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License along with
18 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
19 # Suite 330, Boston, MA  02111-1307 USA
20
21 use CGI;
22 use strict;
23 use C4::Auth;
24 use C4::Output;
25 use C4::Biblio;
26 use C4::Context;
27 use C4::Koha; # XXX subfield_is_koha_internal_p
28 use Date::Calc qw(Today);
29
30 use MARC::File::XML;
31
32 sub find_value {
33     my ($tagfield,$insubfield,$record) = @_;
34     my $result;
35     my $indicator;
36     foreach my $field ($record->field($tagfield)) {
37         my @subfields = $field->subfields();
38         foreach my $subfield (@subfields) {
39             if (@$subfield[0] eq $insubfield) {
40                 $result .= @$subfield[1];
41                 $indicator = $field->indicator(1).$field->indicator(2);
42             }
43         }
44     }
45     return($indicator,$result);
46 }
47
48 sub get_item_from_barcode {
49     my ($barcode)=@_;
50     my $dbh=C4::Context->dbh;
51     my $result;
52     my $rq=$dbh->prepare("SELECT itemnumber from items where items.barcode=?");
53     $rq->execute($barcode);
54     ($result)=$rq->fetchrow;
55     return($result);
56 }
57
58 my $input = new CGI;
59 my $dbh = C4::Context->dbh;
60 my $error = $input->param('error');
61 my $biblionumber = $input->param('biblionumber');
62 my $itemnumber = $input->param('itemnumber');
63 my $op = $input->param('op');
64
65 my ($template, $loggedinuser, $cookie)
66     = get_template_and_user({template_name => "cataloguing/additem.tmpl",
67                  query => $input,
68                  type => "intranet",
69                  authnotrequired => 0,
70                  flagsrequired => {editcatalogue => 1},
71                  debug => 1,
72                  });
73
74 # find itemtype
75 my $frameworkcode = &GetFrameworkCode($biblionumber);
76
77 my $tagslib = &GetMarcStructure(1,$frameworkcode);
78 my $record = GetMarcBiblio($biblionumber);
79 my $oldrecord = TransformMarcToKoha($dbh,$record);
80 my $itemrecord;
81 my $nextop="additem";
82 my @errors; # store errors found while checking data BEFORE saving item.
83 #-------------------------------------------------------------------------------
84 if ($op eq "additem") {
85 #-------------------------------------------------------------------------------
86     # rebuild
87     my @tags = $input->param('tag');
88     my @subfields = $input->param('subfield');
89     my @values = $input->param('field_value');
90     # build indicator hash.
91     my @ind_tag = $input->param('ind_tag');
92     my @indicator = $input->param('indicator');
93     my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
94         my $record=MARC::Record::new_from_xml($xml, 'UTF-8');
95     # if autoBarcode is ON, calculate barcode...
96     if (C4::Context->preference('autoBarcode')) {
97         my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
98         unless ($record->field($tagfield)->subfield($tagsubfield)) {
99             my $sth_barcode = $dbh->prepare("select max(abs(barcode)) from items");
100             $sth_barcode->execute;
101             my ($newbarcode) = $sth_barcode->fetchrow;
102             $newbarcode++;
103             # OK, we have the new barcode, now create the entry in MARC record
104             my $fieldItem = $record->field($tagfield);
105             $record->delete_field($fieldItem);
106             $fieldItem->add_subfields($tagsubfield => $newbarcode);
107             $record->insert_fields_ordered($fieldItem);
108         }
109     }
110 # check for item barcode # being unique
111     my $addedolditem = TransformMarcToKoha($dbh,$record);
112     my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
113     push @errors,"barcode_not_unique" if($exist_itemnumber);
114     # if barcode exists, don't create, but report The problem.
115     my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = AddItem($record,$biblionumber) unless ($exist_itemnumber);
116     if ($exist_itemnumber) {
117         $nextop = "additem";
118         $itemrecord = $record;
119     } else {
120         $nextop = "additem";
121     }
122 #-------------------------------------------------------------------------------
123 } elsif ($op eq "edititem") {
124 #-------------------------------------------------------------------------------
125 # retrieve item if exist => then, it's a modif
126     $itemrecord = GetMarcItem($biblionumber,$itemnumber);
127     $nextop="saveitem";
128 #-------------------------------------------------------------------------------
129 } elsif ($op eq "delitem") {
130 #-------------------------------------------------------------------------------
131     # check that there is no issue on this item before deletion.
132     my $sth=$dbh->prepare("select * from issues i where i.returndate is null and i.itemnumber=?");
133     $sth->execute($itemnumber);
134     my $onloan=$sth->fetchrow;
135     push @errors,"book_on_loan" if ($onloan); ##error book_on_loan added to template as well
136     if ($onloan){
137     $nextop="additem";
138     } else {
139         &DelItem($dbh,$biblionumber,$itemnumber);
140         print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode");
141         #$nextop="additem";
142     }
143 #-------------------------------------------------------------------------------
144 } elsif ($op eq "saveitem") {
145 #-------------------------------------------------------------------------------
146     # rebuild
147     my @tags = $input->param('tag');
148     my @subfields = $input->param('subfield');
149     my @values = $input->param('field_value');
150     # build indicator hash.
151     my @ind_tag = $input->param('ind_tag');
152     my @indicator = $input->param('indicator');
153     #    my $itemnumber = $input->param('itemnumber');
154     my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag,'ITEM');
155     $itemrecord=MARC::Record::new_from_xml($xml, 'UTF-8');
156     # MARC::Record builded => now, record in DB
157     # warn "R: ".$record->as_formatted;
158     # check that the barcode don't exist already
159     my $addedolditem = TransformMarcToKoha($dbh,$itemrecord);
160     my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
161     if ($exist_itemnumber && $exist_itemnumber != $itemnumber) {
162         push @errors,"barcode_not_unique";
163     } else {
164         my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = ModItem($itemrecord,$biblionumber,$itemnumber,0);
165     $itemnumber="";
166     }
167     $nextop="additem";
168 }
169
170 #
171 #-------------------------------------------------------------------------------
172 # build screen with existing items. and "new" one
173 #-------------------------------------------------------------------------------
174
175 # now, build existiing item list
176 my $temp = GetMarcBiblio( $biblionumber );
177 my @fields = $temp->fields();
178 #my @fields = $record->fields();
179 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
180 my @big_array;
181 #---- finds where items.itemnumber is stored
182 my ($itemtagfield,$itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber",$frameworkcode);
183 my ($branchtagfield,$branchtagsubfield) = &GetMarcFromKohaField("items.homebranch",$frameworkcode);
184
185 foreach my $field (@fields) {
186     next if ($field->tag()<10);
187     my @subf=$field->subfields;
188     my %this_row;
189 # loop through each subfield
190     for my $i (0..$#subf) {
191         next if ($tagslib->{$field->tag()}->{$subf[$i][0]}->{tab} ne 10 
192                 && ($field->tag() ne $itemtagfield 
193                 && $subf[$i][0] ne $itemtagsubfield));
194
195         $witness{$subf[$i][0]} = $tagslib->{$field->tag()}->{$subf[$i][0]}->{lib} if ($tagslib->{$field->tag()}->{$subf[$i][0]}->{tab}  eq 10);
196
197         $this_row{$subf[$i][0]} =$subf[$i][1] if ($tagslib->{$field->tag()}->{$subf[$i][0]}->{tab}  eq 10);
198         
199         if (($field->tag eq $branchtagfield) && ($subf[$i][$0] eq $branchtagsubfield) && C4::Context->preference("IndependantBranches")) {
200             #verifying rights
201             my $userenv = C4::Context->userenv();
202             unless (($userenv->{'flags'} == 1) or (($userenv->{'branch'} eq $subf[$i][1]))){
203                     $this_row{'nomod'}=1;
204             }
205         }
206         $this_row{itemnumber} = $subf[$i][1] if ($field->tag() eq $itemtagfield && $subf[$i][0] eq $itemtagsubfield);
207     }
208     if (%this_row) {
209         push(@big_array, \%this_row);
210     }
211 }
212 #fill big_row with missing data
213 foreach my $subfield_code  (keys(%witness)) {
214     for (my $i=0;$i<=$#big_array;$i++) {
215         $big_array[$i]{$subfield_code}="&nbsp;" unless ($big_array[$i]{$subfield_code});
216     }
217 }
218 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField("items.holdingbranch",$frameworkcode);
219 @big_array = sort {$a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf}} @big_array;
220
221 # now, construct template !
222 # First, the existing items for display
223 my @item_value_loop;
224 my @header_value_loop;
225 for (my $i=0;$i<=$#big_array; $i++) {
226     my $items_data;
227     foreach my $subfield_code (sort keys(%witness)) {
228         $items_data .="<td>".$big_array[$i]{$subfield_code}."</td>";
229     }
230     my %row_data;
231     $items_data =~ s/"/&quot;/g;
232     $row_data{item_value} = $items_data;
233     $row_data{itemnumber} = $big_array[$i]->{itemnumber};
234     #reporting this_row values
235     $row_data{'nomod'} = $big_array[$i]{'nomod'};
236     push(@item_value_loop,\%row_data);
237 }
238 foreach my $subfield_code (sort keys(%witness)) {
239     my %header_value;
240     $header_value{header_value} = $witness{$subfield_code};
241     push(@header_value_loop, \%header_value);
242 }
243
244 # now, build the item form for entering a new item
245 my @loop_data =();
246 my $i=0;
247 my $authorised_values_sth = $dbh->prepare("SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib");
248
249 foreach my $tag (sort keys %{$tagslib}) {
250   my $previous_tag = '';
251 # loop through each subfield
252   foreach my $subfield (sort keys %{$tagslib->{$tag}}) {
253     next if subfield_is_koha_internal_p($subfield);
254     next if ($tagslib->{$tag}->{$subfield}->{'tab'}  ne "10");
255     my %subfield_data;
256  
257     my $index_subfield= int(rand(1000000)); 
258     if($subfield eq '@'){
259         $subfield_data{id} = "tag_".$tag."_subfield_0_".$index_subfield;
260     } else {
261          $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".$index_subfield;
262     }
263     $subfield_data{tag}=$tag;
264     $subfield_data{subfield}=$subfield;
265     $subfield_data{random}=int(rand(1000000)); 
266 #        $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
267     $subfield_data{marc_lib}="<span id=\"error$i\" title=\"".$tagslib->{$tag}->{$subfield}->{lib}."\">".$tagslib->{$tag}->{$subfield}->{lib}."</span>";
268     $subfield_data{mandatory}=$tagslib->{$tag}->{$subfield}->{mandatory};
269     $subfield_data{repeatable}=$tagslib->{$tag}->{$subfield}->{repeatable};
270     my ($x,$value);
271     ($x,$value) = find_value($tag,$subfield,$itemrecord) if ($itemrecord);
272     $value =~ s/"/&quot;/g;
273     unless ($value) {
274         $value = $tagslib->{$tag}->{$subfield}->{defaultvalue};
275
276         # get today date & replace YYYY, MM, DD if provided in the default value
277         my ( $year, $month, $day ) = Today();
278         $month = sprintf( "%02d", $month );
279         $day   = sprintf( "%02d", $day );
280         $value =~ s/YYYY/$year/g;
281         $value =~ s/MM/$month/g;
282         $value =~ s/DD/$day/g;
283     }
284     $subfield_data{visibility} = "display:none;" if (($tagslib->{$tag}->{$subfield}->{hidden} % 2 == 1));
285     #testing branch value if IndependantBranches.
286     my $test = (C4::Context->preference("IndependantBranches")) &&
287               ($tag eq $branchtagfield) && ($subfield eq $branchtagsubfield) &&
288               (C4::Context->userenv->{flags} != 1) && ($value) && ($value ne C4::Context->userenv->{branch}) ;
289 #         print $input->redirect(".pl?biblionumber=$biblionumber") if ($test);
290         # search for itemcallnumber if applicable
291     if (!$value && $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.itemcallnumber' && C4::Context->preference('itemcallnumber')) {
292         my $CNtag = substr(C4::Context->preference('itemcallnumber'),0,3);
293         my $CNsubfield = substr(C4::Context->preference('itemcallnumber'),3,1);
294         my $CNsubfield2 = substr(C4::Context->preference('itemcallnumber'),4,1);
295         my $temp2 = $temp->field($CNtag);
296         if ($temp2) {
297                 $value = ($temp2->subfield($CNsubfield)).' '.($temp2->subfield($CNsubfield2));
298 #remove any trailing space incase one subfield is used
299         $value=~s/^\s+|\s+$//g;
300       }
301     }
302     if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
303       my @authorised_values;
304       my %authorised_lib;
305       my $dbh=C4::Context->dbh;   
306   
307       # builds list, depending on authorised value...
308   
309       #---- branch
310       if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
311           my $sth =
312             $dbh->prepare(
313               "select branchcode,branchname from branches order by branchname");
314           $sth->execute;
315           push @authorised_values, ""
316             unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
317   
318           while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
319               push @authorised_values, $branchcode;
320               $authorised_lib{$branchcode} = $branchname;
321           }
322   
323           #----- itemtypes
324       }
325       elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
326           my $sth =
327             $dbh->prepare(
328               "select itemtype,description from itemtypes order by description");
329           $sth->execute;
330           push @authorised_values, ""
331             unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
332             
333           my $itemtype;
334           
335           while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
336               push @authorised_values, $itemtype;
337               $authorised_lib{$itemtype} = $description;
338           }
339           $value = $itemtype unless ($value);
340   
341           #---- "true" authorised value
342       }
343       else {
344           $authorised_values_sth->execute(
345               $tagslib->{$tag}->{$subfield}->{authorised_value} );
346   
347           push @authorised_values, ""
348             unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
349   
350           while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
351               push @authorised_values, $value;
352               $authorised_lib{$value} = $lib;
353           }
354       }
355       $subfield_data{marc_value} =CGI::scrolling_list(
356           -name     => "field_value",
357           -values   => \@authorised_values,
358           -default  => $value,
359           -labels   => \%authorised_lib,
360           -override => 1,
361           -size     => 1,
362           -multiple => 0,
363           -tabindex => 1,
364           -id       => "tag_".$tag."_subfield_".$subfield."_".$index_subfield,
365           -class    => "input_marceditor",
366       );
367     # it's a thesaurus / authority field
368     }
369     elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode} ) {
370         $subfield_data{marc_value} =
371             "<input type=\"text\"
372                     id=\"".$subfield_data{id}."\"
373                     name=\"field_value\"
374                     value=\"$value\"
375                     class=\"input_marceditor\"
376                     tabindex=\"1\"
377                     size=\"67\"
378                     maxlength=\"255\" 
379                     \/>
380                     <a href=\"#\" class=\"buttonDot\"
381                         onclick=\"Dopop('/cgi-bin/koha/authorities/auth_finder.pl?authtypecode=".$tagslib->{$tag}->{$subfield}->{authtypecode}."&index=$subfield_data{id}','$subfield_data{id}'); return false;\" title=\"Tag Editor\">...</a>
382     ";
383     # it's a plugin field
384     }
385     elsif ( $tagslib->{$tag}->{$subfield}->{'value_builder'} ) {
386
387         # opening plugin. Just check wether we are on a developper computer on a production one
388         # (the cgidir differs)
389         my $cgidir = C4::Context->intranetdir . "/cgi-bin/cataloguing/value_builder";
390         unless ( opendir( DIR, "$cgidir" ) ) {
391             $cgidir = C4::Context->intranetdir . "/cataloguing/value_builder";
392         }
393         my $plugin = $cgidir . "/" . $tagslib->{$tag}->{$subfield}->{'value_builder'};
394         do $plugin || die "Plugin Failed: ".$plugin;
395         my $extended_param = plugin_parameters( $dbh, $temp, $tagslib, $subfield_data{id}, \@loop_data );
396         my ( $function_name, $javascript ) = plugin_javascript( $dbh, $temp, $tagslib, $subfield_data{id}, \@loop_data );
397 #         my ( $function_name, $javascript,$extended_param );
398         
399         $subfield_data{marc_value} =
400                 "<input tabindex=\"1\"
401                         type=\"text\"
402                         id=\"".$subfield_data{id}."\"
403                         name=\"field_value\"
404                         value=\"$value\"
405                         class=\"input_marceditor\"
406                         onfocus=\"Focus$function_name(".$subfield_data{random}.")\"
407                         size=\"67\"
408                         maxlength=\"255\" 
409                         onblur=\"Blur$function_name(".$subfield_data{random}."); \" \/>
410                         <a href=\"#\" class=\"buttonDot\" onclick=\"Clic$function_name('$subfield_data{id}'; return false;)\" title=\"Tag Editor\">...</a>
411                 $javascript";
412         # it's an hidden field
413     }
414     elsif ( $tag eq '' ) {
415         $subfield_data{marc_value} =
416             "<input tabindex=\"1\"
417                     type=\"hidden\"
418                     id=\"".$subfield_data{id}."\"
419                     name=\"field_value\"
420                     size=\"67\"
421                     maxlength=\"255\" 
422                     value=\"$value\" \/>
423             ";
424     }
425     elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) {
426         $subfield_data{marc_value} =
427             "<input type=\"text\"
428                     id=\"".$subfield_data{id}."\"
429                     name=\"field_value\"
430                     class=\"input_marceditor\"
431                     tabindex=\"1\"
432                     size=\"67\"
433                     maxlength=\"255\" 
434                     value=\"$value\"
435             \/>";
436
437         # it's a standard field
438     }
439     else {
440         if (
441             length($value) > 100
442             or
443             ( C4::Context->preference("marcflavour") eq "UNIMARC" && $tag >= 300
444                 and $tag < 400 && $subfield eq 'a' )
445             or (    $tag >= 500
446                 and $tag < 600
447                 && C4::Context->preference("marcflavour") eq "MARC21" )
448           )
449         {
450             $subfield_data{marc_value} =
451                 "<textarea cols=\"70\"
452                            rows=\"4\"
453                            id=\"".$subfield_data{id}."\"
454                            name=\"field_value\"
455                            class=\"input_marceditor\"
456                            tabindex=\"1\"
457                             size=\"67\"
458                             maxlength=\"255\" 
459                            >$value</textarea>
460                 ";
461         }
462         else {
463             $subfield_data{marc_value} =
464                 "<input type=\"text\"
465                         id=\"".$subfield_data{id}."\"
466                         name=\"field_value\"
467                         value=\"$value\"
468                         tabindex=\"1\"
469                         size=\"67\"
470                         maxlength=\"255\" 
471                         class=\"input_marceditor\"
472                 \/>
473                 ";
474         }
475     }
476 #        $subfield_data{marc_value}="<input type=\"text\" name=\"field_value\">";
477         push(@loop_data, \%subfield_data);
478         $i++
479     }
480 }
481
482 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
483 $template->param( title => $record->title() ) if ($record ne "-1");
484 $template->param(item_loop => \@item_value_loop,
485                         item_header_loop => \@header_value_loop,
486                         biblionumber => $biblionumber,
487                         title => $oldrecord->{title},
488                         author => $oldrecord->{author},
489                         item => \@loop_data,
490                         itemnumber => $itemnumber,
491                         itemtagfield => $itemtagfield,
492                         itemtagsubfield =>$itemtagsubfield,
493                         op => $nextop,
494                         opisadd => ($nextop eq "saveitem")?0:1);
495 foreach my $error (@errors) {
496     $template->param($error => 1);
497 }
498 output_html_with_http_headers $input, $cookie, $template->output;