Bug 2044: allowing multiuple icon sets
[koha.git] / admin / itemtypes.pl
1 #!/usr/bin/perl
2
3 # Copyright 2000-2002 Katipo Communications
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA  02111-1307 USA
19
20 =head1 admin/itemtypes.pl
21
22 script to administer the categories table
23 written 20/02/2002 by paul.poulain@free.fr
24  This software is placed under the gnu General Public License, v2 (http://www.gnu.org/licenses/gpl.html)
25
26  ALGO :
27  this script use an $op to know what to do.
28  if $op is empty or none of the above values,
29         - the default screen is build (with all records, or filtered datas).
30         - the   user can clic on add, modify or delete record.
31  if $op=add_form
32         - if primkey exists, this is a modification,so we read the $primkey record
33         - builds the add/modify form
34  if $op=add_validate
35         - the user has just send datas, so we create/modify the record
36  if $op=delete_form
37         - we show the record having primkey=$primkey and ask for deletion validation form
38  if $op=delete_confirm
39         - we delete the record having primkey=$primkey
40
41 =cut
42
43 use strict;
44 use CGI;
45
46 use List::Util qw/min/;
47 use File::Spec;
48
49 use C4::Koha;
50 use C4::Context;
51 use C4::Auth;
52 use C4::Output;
53
54 sub StringSearch {
55     my ( $searchstring, $type ) = @_;
56     my $dbh = C4::Context->dbh;
57     $searchstring =~ s/\'/\\\'/g;
58     my @data = split( ' ', $searchstring );
59     my $sth = $dbh->prepare(
60         "SELECT * FROM itemtypes WHERE (description LIKE ?) ORDER BY itemtype"
61         );
62     $sth->execute("$data[0]%");
63     return $sth->fetchall_arrayref({});         # return ref-to-array of ref-to-hashes
64                                                                 # like [ fetchrow_hashref(), fetchrow_hashref() ... ]
65 }
66
67 sub getImagesFromDirectory {
68     my $directoryname = shift;
69     return unless defined $directoryname;
70     return unless -d $directoryname;
71
72     if ( opendir ( my $dh, $directoryname ) ) {
73         my @images = grep { /\.(gif|png)$/i } readdir( $dh );
74         closedir $dh;
75         return @images;
76     } else {
77         warn "unable to opendir $directoryname: $!";
78         return;
79     }
80 }
81 sub getSubdirectoryNames {
82     my $directoryname = shift;
83     return unless defined $directoryname;
84     return unless -d $directoryname;
85
86     if ( opendir ( my $dh, $directoryname ) ) {
87         my @directories = grep { -d File::Spec->catfile( $directoryname, $_ ) && ! ( /^\./ ) } readdir( $dh );
88         closedir $dh;
89         return @directories;
90     } else {
91         warn "unable to opendir $directoryname: $!";
92         return;
93     }
94 }
95
96 my $input       = new CGI;
97 my $searchfield = $input->param('description');
98 my $script_name = "/cgi-bin/koha/admin/itemtypes.pl";
99 my $itemtype    = $input->param('itemtype');
100 my $pagesize    = 10;
101 my $op          = $input->param('op');
102 $searchfield =~ s/\,//g;
103 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
104     {
105         template_name   => "admin/itemtypes.tmpl",
106         query           => $input,
107         type            => "intranet",
108         authnotrequired => 0,
109         flagsrequired   => { parameters => 1 },
110         debug           => 1,
111     }
112 );
113
114 $template->param(script_name => $script_name);
115 if ($op) {
116         $template->param($op  => 1); # we show only the TMPL_VAR names $op
117 } else {
118     $template->param(else => 1);
119 }
120
121 my $dbh = C4::Context->dbh;
122
123 ################## ADD_FORM ##################################
124 # called by default. Used to create form to add or  modify a record
125 if ( $op eq 'add_form' ) {
126     #---- if primkey exists, it's a modify action, so read values to modify...
127     my $data;
128     if ($itemtype) {
129         my $sth = $dbh->prepare("select * from itemtypes where itemtype=?");
130         $sth->execute($itemtype);
131         $data = $sth->fetchrow_hashref;
132     }
133
134     # build list of images
135     my $src = "intranet"; # so that the getitemtypeimage functions know where they were called from -fbcit
136     my $imagedir_filesystem = getitemtypeimagedir($src);
137     my $imagedir_web        = getitemtypeimagesrc($src);
138
139     my @imagesets = (); # list of hasrefs of image set data to pass to template
140     my @subdirectories = getSubdirectoryNames( $imagedir_filesystem );
141
142     foreach my $imagesubdir ( @subdirectories ) {
143         my @imagelist     = (); # hashrefs of image info
144         my $i              = 0; # counter
145         my $image_per_line = 12; # max images in a line?
146         my @imagenames = getImagesFromDirectory( File::Spec->catfile( $imagedir_filesystem, $imagesubdir ) );
147         foreach my $thisimage ( @imagenames ) {
148             $i++;
149             if ( $i == $image_per_line ) {
150                 $i = 0;
151                 push @imagelist, { KohaImage => '', KohaImageSrc => '' };
152             } else {
153                 push(
154                      @imagelist,
155                      {
156                       KohaImage    => "$imagesubdir/$thisimage",
157                       KohaImageSrc => join( '/', $imagedir_web, $imagesubdir, $thisimage ),
158                       checked      => "$imagesubdir/$thisimage" eq $data->{imageurl} ? 1 : 0,
159                   }
160                  );
161             }
162         }
163         push @imagesets, { imagesetname => $imagesubdir,
164                            images       => \@imagelist };
165         
166     }
167
168     my $remote_image = undef;
169     if ( defined $data->{imageurl} and $data->{imageurl} =~ /^http/i ) {
170         $remote_image = $data->{imageurl};
171     }
172
173     $template->param(
174         itemtype        => $itemtype,
175         description     => $data->{'description'},
176         renewalsallowed => $data->{'renewalsallowed'},
177         rentalcharge    => sprintf( "%.2f", $data->{'rentalcharge'} ),
178         notforloan      => $data->{'notforloan'},
179         imageurl        => $data->{'imageurl'},
180         template        => C4::Context->preference('template'),
181         summary         => $data->{summary},
182         imagesets       => \@imagesets,
183         remote_image    => $remote_image,
184     );
185
186     # END $OP eq ADD_FORM
187 ################## ADD_VALIDATE ##################################
188     # called by add_form, used to insert/modify data in DB
189 }
190 elsif ( $op eq 'add_validate' ) {
191     my $query = "
192         SELECT itemtype
193         FROM   itemtypes
194         WHERE  itemtype = ?
195     ";
196     my $sth = $dbh->prepare($query);
197     $sth->execute($itemtype);
198     if ( $sth->fetchrow ) {             # it's a modification
199         my $query2 = '
200             UPDATE itemtypes
201             SET    description = ?
202                  , renewalsallowed = ?
203                  , rentalcharge = ?
204                  , notforloan = ?
205                  , imageurl = ?
206                  , summary = ?
207             WHERE itemtype = ?
208         ';
209         $sth = $dbh->prepare($query2);
210         $sth->execute(
211             $input->param('description'),
212             $input->param('renewalsallowed'),
213             $input->param('rentalcharge'),
214             ( $input->param('notforloan') ? 1 : 0 ),
215             (
216                 $input->param('image') eq 'removeImage' ? '' : (
217                       $input->param('image') eq 'remoteImage'
218                     ? $input->param('remoteImage')
219                     : $input->param('image') . ""
220                 )
221             ),
222             $input->param('summary'),
223             $input->param('itemtype')
224         );
225     }
226     else {    # add a new itemtype & not modif an old
227         my $query = "
228             INSERT INTO itemtypes
229                 (itemtype,description,renewalsallowed,rentalcharge, notforloan, imageurl,summary)
230             VALUES
231                 (?,?,?,?,?,?,?);
232             ";
233         my $sth = $dbh->prepare($query);
234                 my $image = $input->param('image');
235         $sth->execute(
236             $input->param('itemtype'),
237             $input->param('description'),
238             $input->param('renewalsallowed'),
239             $input->param('rentalcharge'),
240             $input->param('notforloan') ? 1 : 0,
241             $image eq 'removeImage' ?           ''                 :
242             $image eq 'remoteImage' ? $input->param('remoteImage') :
243             $image,
244             $input->param('summary'),
245         );
246     }
247
248     print $input->redirect('itemtypes.pl');
249     exit;
250
251     # END $OP eq ADD_VALIDATE
252 ################## DELETE_CONFIRM ##################################
253     # called by default form, used to confirm deletion of data in DB
254 }
255 elsif ( $op eq 'delete_confirm' ) {
256     # Check both categoryitem and biblioitems, see Bug 199
257     my $total = 0;
258     for my $table ('biblioitems') {
259         my $sth =
260           $dbh->prepare(
261             "select count(*) as total from $table where itemtype=?");
262         $sth->execute($itemtype);
263         $total += $sth->fetchrow_hashref->{total};
264     }
265
266     my $sth =
267       $dbh->prepare(
268 "select itemtype,description,renewalsallowed,rentalcharge from itemtypes where itemtype=?"
269       );
270     $sth->execute($itemtype);
271     my $data = $sth->fetchrow_hashref;
272     $template->param(
273         itemtype        => $itemtype,
274         description     => $data->{description},
275         renewalsallowed => $data->{renewalsallowed},
276         rentalcharge    => sprintf( "%.2f", $data->{rentalcharge} ),
277         imageurl        => $data->{imageurl},
278         total           => $total
279     );
280
281     # END $OP eq DELETE_CONFIRM
282 ################## DELETE_CONFIRMED ##################################
283   # called by delete_confirm, used to effectively confirm deletion of data in DB
284 }
285 elsif ( $op eq 'delete_confirmed' ) {
286     my $itemtype = uc( $input->param('itemtype') );
287     my $sth      = $dbh->prepare("delete from itemtypes where itemtype=?");
288     $sth->execute($itemtype);
289     $sth = $dbh->prepare("delete from issuingrules where itemtype=?");
290     $sth->execute($itemtype);
291     print $input->redirect('itemtypes.pl');
292     exit;
293     # END $OP eq DELETE_CONFIRMED
294 ################## DEFAULT ##################################
295 }
296 else {    # DEFAULT
297     my ($results) = StringSearch( $searchfield, 'web' );
298     my $page = $input->param('page') || 1;
299     my $first = ( $page - 1 ) * $pagesize;
300
301     # if we are on the last page, the number of the last word to display
302     # must not exceed the length of the results array
303     my $last = min( $first + $pagesize - 1, scalar @{$results} - 1, );
304     my $toggle = 0;
305     my @loop;
306     foreach my $itemtype ( @{$results}[ $first .. $last ] ) {
307         $itemtype->{toggle} = ($toggle++ % 2) ? 0 : 1 ;
308         $itemtype->{imageurl} = getitemtypeimagesrc('intranet') . "/$itemtype->{imageurl}";
309         $itemtype->{rentalcharge} = sprintf( '%.2f', $itemtype->{rentalcharge} );
310         push( @loop, $itemtype );
311     }
312
313     $template->param(
314         loop           => \@loop,
315         pagination_bar => pagination_bar(
316             $script_name, getnbpages( scalar @{$results}, $pagesize ),
317             $page,        'page'
318         )
319     );
320 }    #---- END $OP eq DEFAULT
321
322 output_html_with_http_headers $input, $cookie, $template->output;