Bug 28409: Comprehensively validate category in opac-shelves.pl
[koha.git] / opac / opac-shelves.pl
1 #!/usr/bin/perl
2
3 # Copyright 2015 Koha Team
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 use Modern::Perl;
21
22 use CGI qw ( -utf8 );
23 use C4::Auth;
24 use C4::Biblio;
25 use C4::External::BakerTaylor qw( image_url link_url );
26 use C4::Koha;
27 use C4::Items;
28 use C4::Members;
29 use C4::Output;
30 use C4::Tags qw( get_tags );
31 use C4::XSLT;
32
33 use Koha::Biblios;
34 use Koha::Biblioitems;
35 use Koha::CirculationRules;
36 use Koha::CsvProfiles;
37 use Koha::Items;
38 use Koha::ItemTypes;
39 use Koha::Patrons;
40 use Koha::Virtualshelves;
41 use Koha::RecordProcessor;
42
43 use constant ANYONE => 2;
44
45 my $query = CGI->new;
46
47 my $template_name = $query->param('rss') ? "opac-shelves-rss.tt" : "opac-shelves.tt";
48
49 # if virtualshelves is disabled, leave immediately
50 if ( ! C4::Context->preference('virtualshelves') ) {
51     print $query->redirect("/cgi-bin/koha/errors/404.pl");
52     exit;
53 }
54
55 my $op = $query->param('op') || 'list';
56 my ( $template, $loggedinuser, $cookie );
57
58 if( $op eq 'view' || $op eq 'list' ){
59     ( $template, $loggedinuser, $cookie ) = get_template_and_user({
60             template_name   => $template_name,
61             query           => $query,
62             type            => "opac",
63             authnotrequired => ( C4::Context->preference("OpacPublic") ? 1 : 0 ),
64         });
65 } else {
66     ( $template, $loggedinuser, $cookie ) = get_template_and_user({
67             template_name   => $template_name,
68             query           => $query,
69             type            => "opac",
70             authnotrequired => 0,
71         });
72 }
73
74 if (C4::Context->preference("BakerTaylorEnabled")) {
75     $template->param(
76         BakerTaylorImageURL => &image_url(),
77         BakerTaylorLinkURL  => &link_url(),
78     );
79 }
80
81 my $referer  = $query->param('referer')  || $op;
82 my $category = 1;
83 if ( $query->param('category') && (
84             ($query->param('category') == 1) ||
85             ($query->param('category') == 2)
86         )
87     ){
88     $category = $query->param('category');
89 }
90
91 my ( $shelf, $shelfnumber, @messages );
92
93 if ( $op eq 'add_form' ) {
94     # Only pass default
95     $shelf = { allow_change_from_owner => 1 };
96 } elsif ( $op eq 'edit_form' ) {
97     $shelfnumber = $query->param('shelfnumber');
98     $shelf       = Koha::Virtualshelves->find($shelfnumber);
99
100     if ( $shelf ) {
101         $category = $shelf->category;
102         my $patron = Koha::Patrons->find( $shelf->owner );
103         $template->param( owner => $patron, );
104         unless ( $shelf->can_be_managed( $loggedinuser ) ) {
105             push @messages, { type => 'error', code => 'unauthorized_on_update' };
106             $op = 'list';
107         }
108     } else {
109         push @messages, { type => 'error', code => 'does_not_exist' };
110     }
111 } elsif ( $op eq 'add' ) {
112     if ( $loggedinuser ) {
113         my $allow_changes_from = $query->param('allow_changes_from');
114         eval {
115             $shelf = Koha::Virtualshelf->new(
116                 {   shelfname          => scalar $query->param('shelfname'),
117                     sortfield          => scalar $query->param('sortfield'),
118                     category           => $category || 1,
119                     allow_change_from_owner => $allow_changes_from > 0,
120                     allow_change_from_others => $allow_changes_from == ANYONE,
121                     owner              => scalar $loggedinuser,
122                 }
123             );
124             $shelf->store;
125             $shelfnumber = $shelf->shelfnumber;
126         };
127         if ($@) {
128             push @messages, { type => 'error', code => ref($@), msg => $@ };
129         } elsif ( not $shelf ) {
130             push @messages, { type => 'error', code => 'error_on_insert' };
131         } else {
132             push @messages, { type => 'message', code => 'success_on_insert' };
133             $op = 'view';
134         }
135     } else {
136         push @messages, { type => 'error', code => 'unauthorized_on_insert' };
137         $op = 'list';
138     }
139 } elsif ( $op eq 'edit' ) {
140     $shelfnumber = $query->param('shelfnumber');
141     $shelf       = Koha::Virtualshelves->find($shelfnumber);
142     if ( $shelf ) {
143         $op = $referer;
144         my $sortfield = $query->param('sortfield');
145         $sortfield = 'title' unless grep { $_ eq $sortfield } qw( title author copyrightdate itemcallnumber dateadded );
146         if ( $shelf->can_be_managed( $loggedinuser ) ) {
147             $shelf->shelfname( scalar $query->param('shelfname') );
148             $shelf->sortfield( $sortfield );
149             my $allow_changes_from = $query->param('allow_changes_from');
150             $shelf->allow_change_from_owner( $allow_changes_from > 0 );
151             $shelf->allow_change_from_others( $allow_changes_from == ANYONE );
152             $shelf->category( $category );
153             eval { $shelf->store };
154
155             if ($@) {
156                 push @messages, { type => 'error', code => 'error_on_update' };
157                 $op = 'edit_form';
158             } else {
159                 push @messages, { type => 'message', code => 'success_on_update' };
160             }
161         } else {
162             push @messages, { type => 'error', code => 'unauthorized_on_update' };
163         }
164     } else {
165         push @messages, { type => 'error', code => 'does_not_exist' };
166     }
167 } elsif ( $op eq 'delete' ) {
168     $shelfnumber = $query->param('shelfnumber');
169     $shelf       = Koha::Virtualshelves->find($shelfnumber);
170     if ($shelf) {
171         if ( $shelf->can_be_deleted( $loggedinuser ) ) {
172             eval { $shelf->delete; };
173             if ($@) {
174                 push @messages, { type => 'error', code => ref($@), msg => $@ };
175             } else {
176                 push @messages, { type => 'message', code => 'success_on_delete' };
177             }
178         } else {
179             push @messages, { type => 'error', code => 'unauthorized_on_delete' };
180         }
181     } else {
182         push @messages, { type => 'error', code => 'does_not_exist' };
183     }
184     $op = $referer;
185 } elsif ( $op eq 'remove_share' ) {
186     $shelfnumber = $query->param('shelfnumber');
187     $shelf = Koha::Virtualshelves->find($shelfnumber);
188     if ($shelf) {
189         my $removed = eval { $shelf->remove_share( $loggedinuser ); };
190         if ($@) {
191             push @messages, { type => 'error', code => ref($@), msg => $@ };
192         } elsif ( $removed ) {
193             push @messages, { type => 'message', code => 'success_on_remove_share' };
194         } else {
195             push @messages, { type => 'error', code => 'error_on_remove_share' };
196         }
197     } else {
198         push @messages, { type => 'error', code => 'does_not_exist' };
199     }
200     $op = $referer;
201
202 } elsif ( $op eq 'add_biblio' ) {
203     $shelfnumber = $query->param('shelfnumber');
204     $shelf = Koha::Virtualshelves->find($shelfnumber);
205     if ($shelf) {
206         if( my $barcode = $query->param('barcode') ) {
207             my $item = Koha::Items->find({ barcode => $barcode });
208             if ( $item ) {
209                 if ( $shelf->can_biblios_be_added( $loggedinuser ) ) {
210                     my $added = eval { $shelf->add_biblio( $item->biblionumber, $loggedinuser ); };
211                     if ($@) {
212                         push @messages, { type => 'error', code => ref($@), msg => $@ };
213                     } elsif ( $added ) {
214                         push @messages, { type => 'message', code => 'success_on_add_biblio' };
215                     } else {
216                         push @messages, { type => 'message', code => 'error_on_add_biblio' };
217                     }
218                 } else {
219                     push @messages, { type => 'error', code => 'unauthorized_on_add_biblio' };
220                 }
221             } else {
222                 push @messages, { type => 'error', code => 'item_does_not_exist' };
223             }
224         }
225     } else {
226         push @messages, { type => 'error', code => 'does_not_exist' };
227     }
228     $op = $referer;
229 } elsif ( $op eq 'remove_biblios' ) {
230     $shelfnumber = $query->param('shelfnumber');
231     $shelf = Koha::Virtualshelves->find($shelfnumber);
232     my @biblionumber = $query->multi_param('biblionumber');
233     if ($shelf) {
234         if ( $shelf->can_biblios_be_removed( $loggedinuser ) ) {
235             my $number_of_biblios_removed = eval {
236                 $shelf->remove_biblios(
237                     {
238                         biblionumbers => \@biblionumber,
239                         borrowernumber => $loggedinuser,
240                     }
241                 );
242             };
243             if ($@) {
244                 push @messages, { type => 'error', code => ref($@), msg => $@ };
245             } elsif ( $number_of_biblios_removed ) {
246                 push @messages, { type => 'message', code => 'success_on_remove_biblios' };
247             } else {
248                 push @messages, { type => 'error', code => 'no_biblio_removed' };
249             }
250         } else {
251             push @messages, { type => 'error', code => 'unauthorized_on_remove_biblios' };
252         }
253     } else {
254         push @messages, { type => 'error', code => 'does_not_exist' };
255     }
256     $op = 'view';
257 }
258
259 if ( $op eq 'view' ) {
260     $shelfnumber ||= $query->param('shelfnumber');
261     $shelf = Koha::Virtualshelves->find($shelfnumber);
262     if ( $shelf ) {
263         if ( $shelf->can_be_viewed( $loggedinuser ) ) {
264             $category = $shelf->category;
265             my( $sortfield, $direction );
266             if( defined( $query->param('sortfield') ) ){ # Passed in sorting overrides default sorting
267                 ( $sortfield, $direction ) = split /:/, $query->param('sortfield');
268             } else {
269                 $sortfield = $shelf->sortfield;
270                 $direction = 'asc';
271             }
272             $sortfield = 'title' unless grep $_ eq $sortfield, qw( title author copyrightdate itemcallnumber dateadded );
273             $direction = 'asc' if $direction ne 'asc' and $direction ne 'desc';
274             my ( $page, $rows );
275             unless ( $query->param('print') or $query->param('rss') ) {
276                 $rows = C4::Context->preference('OPACnumSearchResults') || 20;
277                 $page = ( $query->param('page') ? $query->param('page') : 1 );
278             }
279             my $order_by = $sortfield eq 'itemcallnumber' ? 'items.cn_sort' : $sortfield;
280             my $contents = $shelf->get_contents->search(
281                 {},
282                 {
283                     prefetch => [ { 'biblionumber' => { 'biblioitems' => 'items' } } ],
284                     page     => $page,
285                     rows     => $rows,
286                     order_by => { "-$direction" => $order_by },
287                 }
288             );
289
290             # get biblionumbers stored in the cart
291             my @cart_list;
292             if(my $cart_list = $query->cookie('bib_list')){
293                 @cart_list = split(/\//, $cart_list);
294             }
295
296             my $patron = Koha::Patrons->find( $loggedinuser );
297
298             my $categorycode; # needed for may_article_request
299             if( C4::Context->preference('ArticleRequests') ) {
300                 $categorycode = $patron ? $patron->categorycode : undef;
301             }
302
303             # Lists display falls back to search results configuration
304             my $xslfile = C4::Context->preference('OPACXSLTListsDisplay');
305             my $lang   = $xslfile ? C4::Languages::getlanguage()  : undef;
306             my $sysxml = $xslfile ? C4::XSLT::get_xslt_sysprefs() : undef;
307
308             my $record_processor = Koha::RecordProcessor->new({ filters => 'ViewPolicy' });
309
310             my $art_req_itypes;
311             if( C4::Context->preference('ArticleRequests') ) {
312                 $art_req_itypes = Koha::CirculationRules->guess_article_requestable_itemtypes({ $patron ? ( categorycode => $patron->categorycode ) : () });
313             }
314
315             my @items;
316             while ( my $content = $contents->next ) {
317                 my $biblionumber = $content->biblionumber;
318                 my $this_item    = GetBiblioData($biblionumber);
319                 my $record = GetMarcBiblio({ biblionumber => $biblionumber });
320                 my $framework = GetFrameworkCode( $biblionumber );
321                 my $biblio = Koha::Biblios->find( $biblionumber );
322                 $record_processor->options({
323                     interface => 'opac',
324                     frameworkcode => $framework
325                 });
326                 $record_processor->process($record);
327
328                 if ($xslfile) {
329                     my $variables = {
330                         anonymous_session => ($loggedinuser) ? 0 : 1
331                     };
332                     $this_item->{XSLTBloc} = XSLTParse4Display(
333                         $biblionumber,          $record,
334                         "OPACXSLTListsDisplay", 1,
335                         undef,                  $sysxml,
336                         $xslfile,               $lang,
337                         $variables
338                     );
339                 }
340
341                 my $marcflavour = C4::Context->preference("marcflavour");
342                 my $itemtype = Koha::Biblioitems->search({ biblionumber => $content->biblionumber })->next->itemtype;
343                 $itemtype = Koha::ItemTypes->find( $itemtype );
344                 if( $itemtype ) {
345                     $this_item->{imageurl}          = C4::Koha::getitemtypeimagelocation( 'opac', $itemtype->imageurl );
346                     $this_item->{description}       = $itemtype->description; #FIXME Should not it be translated_description?
347                     $this_item->{notforloan}        = $itemtype->notforloan;
348                 }
349                 $this_item->{'coins'}           = $biblio->get_coins;
350                 $this_item->{'normalized_upc'}  = GetNormalizedUPC( $record, $marcflavour );
351                 $this_item->{'normalized_ean'}  = GetNormalizedEAN( $record, $marcflavour );
352                 $this_item->{'normalized_oclc'} = GetNormalizedOCLCNumber( $record, $marcflavour );
353                 $this_item->{'normalized_isbn'} = GetNormalizedISBN( undef, $record, $marcflavour );
354                 # BZ17530: 'Intelligent' guess if result can be article requested
355                 $this_item->{artreqpossible} = ( $art_req_itypes->{ $this_item->{itemtype} // q{} } || $art_req_itypes->{ '*' } ) ? 1 : q{};
356
357                 unless ( defined $this_item->{size} ) {
358
359                     #TT has problems with size
360                     $this_item->{size} = q||;
361                 }
362
363                 # Getting items infos for location display
364                 my @items_infos = &GetItemsLocationInfo( $biblionumber );
365                 $this_item->{'ITEM_RESULTS'} = \@items_infos;
366
367                 if (C4::Context->preference('TagsEnabled') and C4::Context->preference('TagsShowOnList')) {
368                     $this_item->{TagLoop} = get_tags({
369                         biblionumber => $biblionumber, approved=>1, 'sort'=>'-weight',
370                         limit => C4::Context->preference('TagsShowOnList'),
371                     });
372                 }
373
374                 my $items = $biblio->items;
375                 while ( my $item = $items->next ) {
376                     $this_item->{allow_onshelf_holds} = Koha::CirculationRules->get_onshelfholds_policy( { item => $item, patron => $patron } );
377                     last if $this_item->{allow_onshelf_holds};
378                 }
379
380                 if ( grep {$_ eq $biblionumber} @cart_list) {
381                     $this_item->{incart} = 1;
382                 }
383
384                 $this_item->{biblio_object} = $biblio;
385                 $this_item->{biblionumber}  = $biblionumber;
386                 push @items, $this_item;
387             }
388
389             $template->param(
390                 can_manage_shelf   => $shelf->can_be_managed($loggedinuser),
391                 can_delete_shelf   => $shelf->can_be_deleted($loggedinuser),
392                 can_remove_biblios => $shelf->can_biblios_be_removed($loggedinuser),
393                 can_add_biblios    => $shelf->can_biblios_be_added($loggedinuser),
394                 itemsloop          => \@items,
395                 sortfield          => $sortfield,
396                 direction          => $direction,
397                 csv_profiles => [
398                     Koha::CsvProfiles->search(
399                         { type => 'marc', used_for => 'export_records', staff_only => 0 }
400                     )
401                 ],
402             );
403             if ( $page ) {
404                 my $pager = $contents->pager;
405                 $template->param(
406                     pagination_bar => pagination_bar(
407                         q||, $pager->last_page - $pager->first_page + 1,
408                         $page, "page", { op => 'view', shelfnumber => $shelf->shelfnumber, sortfield => $sortfield, direction => $direction, }
409                     ),
410                 );
411             }
412         } else {
413             push @messages, { type => 'error', code => 'unauthorized_on_view' };
414             undef $shelf;
415         }
416     } else {
417         push @messages, { type => 'error', code => 'does_not_exist' };
418     }
419 }
420
421 if ( $op eq 'list' ) {
422     my $shelves;
423     my ( $page, $rows ) = ( $query->param('page') || 1, 20 );
424     if ( $category == 1 ) {
425         $shelves = Koha::Virtualshelves->get_private_shelves({ page => $page, rows => $rows, borrowernumber => $loggedinuser, });
426     } else {
427         $shelves = Koha::Virtualshelves->get_public_shelves({ page => $page, rows => $rows, });
428     }
429
430     my $pager = $shelves->pager;
431     $template->param(
432         shelves => $shelves,
433         pagination_bar => pagination_bar(
434             q||, $pager->last_page - $pager->first_page + 1,
435             $page, "page", { op => 'list', category => $category, }
436         ),
437     );
438 }
439
440 $template->param(
441     op       => $op,
442     referer  => $referer,
443     shelf    => $shelf,
444     messages => \@messages,
445     category => ($category == 1 || $category == 2) ? $category : "",
446     print    => scalar $query->param('print') || 0,
447     listsview => 1,
448 );
449
450 my $content_type = $query->param('rss')? 'rss' : 'html';
451 output_with_http_headers $query, $cookie, $template->output, $content_type;