Bug 36792: Limit POSIX imports
[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 qw( get_template_and_user );
24 use C4::Biblio qw( GetBiblioData GetFrameworkCode );
25 use C4::External::BakerTaylor qw( image_url link_url );
26 use C4::Koha qw(
27     GetNormalizedEAN
28     GetNormalizedISBN
29     GetNormalizedOCLCNumber
30     GetNormalizedUPC
31 );
32 use C4::Members;
33 use C4::Output qw( pagination_bar output_with_http_headers );
34 use C4::Tags qw( get_tags );
35 use C4::XSLT qw( XSLTParse4Display );
36
37 use Koha::Biblios;
38 use Koha::Biblioitems;
39 use Koha::CirculationRules;
40 use Koha::CsvProfiles;
41 use Koha::DateUtils qw/dt_from_string/;
42 use Koha::Items;
43 use Koha::ItemTypes;
44 use Koha::Patrons;
45 use Koha::Virtualshelfshares;
46 use Koha::Virtualshelves;
47 use Koha::RecordProcessor;
48
49 use constant ANYONE => 2;
50 use constant STAFF => 3;
51 use constant PERMITTED => 4;
52
53 my $query = CGI->new;
54
55 my $template_name = $query->param('rss') ? "opac-shelves-rss.tt" : "opac-shelves.tt";
56
57 # if virtualshelves is disabled, leave immediately
58 if ( ! C4::Context->preference('virtualshelves') ) {
59     print $query->redirect("/cgi-bin/koha/errors/404.pl");
60     exit;
61 }
62
63 my $op = $query->param('op') || 'list';
64 my ( $template, $loggedinuser, $cookie );
65
66 if( $op eq 'view' || $op eq 'list' ){
67     ( $template, $loggedinuser, $cookie ) = get_template_and_user({
68             template_name   => $template_name,
69             query           => $query,
70             type            => "opac",
71             authnotrequired => ( C4::Context->preference("OpacPublic") ? 1 : 0 ),
72         });
73 } else {
74     ( $template, $loggedinuser, $cookie ) = get_template_and_user({
75             template_name   => $template_name,
76             query           => $query,
77             type            => "opac",
78             authnotrequired => 0,
79         });
80 }
81
82 if (C4::Context->preference("BakerTaylorEnabled")) {
83     $template->param(
84         BakerTaylorImageURL => &image_url(),
85         BakerTaylorLinkURL  => &link_url(),
86     );
87 }
88
89 my $referer  = $query->param('referer')  || $op;
90 my $public = 0;
91 $public = 1 if $query->param('public') && $query->param('public') == 1;
92
93 my ( $shelf, $shelfnumber, @messages );
94
95 # PART 1: Perform a few actions
96 if ( $op eq 'add_form' ) {
97     # Only pass default
98     $shelf = { allow_change_from_owner => 1 };
99 } elsif ( $op eq 'edit_form' ) {
100     $shelfnumber = $query->param('shelfnumber');
101     $shelf       = Koha::Virtualshelves->find($shelfnumber);
102
103     if ( $shelf ) {
104         $public = $shelf->public;
105         my $patron = Koha::Patrons->find( $shelf->owner );
106         $template->param( owner => $patron, );
107         unless ( $shelf->can_be_managed( $loggedinuser ) ) {
108             push @messages, { type => 'error', code => 'unauthorized_on_update' };
109             $op = 'list';
110         }
111     } else {
112         push @messages, { type => 'error', code => 'does_not_exist' };
113     }
114 } elsif ( $op eq 'add' ) {
115     if ( $loggedinuser ) {
116         my $allow_changes_from = $query->param('allow_changes_from');
117         eval {
118             $shelf = Koha::Virtualshelf->new(
119                 {   shelfname          => scalar $query->param('shelfname'),
120                     sortfield          => scalar $query->param('sortfield'),
121                     public             => $public,
122                     allow_change_from_owner            => $allow_changes_from > 0,
123                     allow_change_from_others           => $allow_changes_from == ANYONE,
124                     allow_change_from_staff            => $allow_changes_from == STAFF,
125                     allow_change_from_permitted_staff => $allow_changes_from == PERMITTED,
126                     owner              => scalar $loggedinuser,
127                 }
128             );
129             $shelf->store;
130             $shelfnumber = $shelf->shelfnumber;
131         };
132         if ($@) {
133             push @messages, { type => 'error', code => ref($@), msg => $@ };
134         } elsif ( not $shelf ) {
135             push @messages, { type => 'error', code => 'error_on_insert' };
136         } else {
137             push @messages, { type => 'message', code => 'success_on_insert' };
138             $op = 'view';
139         }
140     } else {
141         push @messages, { type => 'error', code => 'unauthorized_on_insert' };
142         $op = 'list';
143     }
144 } elsif ( $op eq 'edit' ) {
145     $shelfnumber = $query->param('shelfnumber');
146     $shelf       = Koha::Virtualshelves->find($shelfnumber);
147     if ( $shelf ) {
148         $op = $referer;
149         my $sortfield = $query->param('sortfield');
150         $sortfield = 'title' unless grep { $_ eq $sortfield } qw( title author copyrightdate itemcallnumber dateadded );
151         if ( $shelf->can_be_managed( $loggedinuser ) ) {
152             $shelf->shelfname( scalar $query->param('shelfname') );
153             $shelf->sortfield( $sortfield );
154             my $allow_changes_from = $query->param('allow_changes_from');
155             $shelf->allow_change_from_owner( $allow_changes_from > 0 );
156             $shelf->allow_change_from_others( $allow_changes_from == ANYONE );
157             $shelf->allow_change_from_staff( $allow_changes_from == STAFF );
158             $shelf->allow_change_from_permitted_staff( $allow_changes_from == PERMITTED );
159             $shelf->public( $public );
160             eval { $shelf->store };
161
162             if ($@) {
163                 push @messages, { type => 'error', code => 'error_on_update' };
164                 $op = 'edit_form';
165             } else {
166                 push @messages, { type => 'message', code => 'success_on_update' };
167             }
168         } else {
169             push @messages, { type => 'error', code => 'unauthorized_on_update' };
170         }
171     } else {
172         push @messages, { type => 'error', code => 'does_not_exist' };
173     }
174 } elsif ( $op eq 'delete' ) {
175     $shelfnumber = $query->param('shelfnumber');
176     $shelf       = Koha::Virtualshelves->find($shelfnumber);
177     if ($shelf) {
178         if ( $shelf->can_be_deleted( $loggedinuser ) ) {
179             eval { $shelf->delete; };
180             if ($@) {
181                 push @messages, { type => 'error', code => ref($@), msg => $@ };
182             } else {
183                 push @messages, { type => 'message', code => 'success_on_delete' };
184             }
185         } else {
186             push @messages, { type => 'error', code => 'unauthorized_on_delete' };
187         }
188     } else {
189         push @messages, { type => 'error', code => 'does_not_exist' };
190     }
191     $op = $referer;
192 } elsif ( $op eq 'remove_share' ) {
193     $shelfnumber = $query->param('shelfnumber');
194     $shelf = Koha::Virtualshelves->find($shelfnumber);
195     if ($shelf) {
196         my $removed = eval { $shelf->remove_share( $loggedinuser ); };
197         if ($@) {
198             push @messages, { type => 'error', code => ref($@), msg => $@ };
199         } elsif ( $removed ) {
200             push @messages, { type => 'message', code => 'success_on_remove_share' };
201         } else {
202             push @messages, { type => 'error', code => 'error_on_remove_share' };
203         }
204     } else {
205         push @messages, { type => 'error', code => 'does_not_exist' };
206     }
207     $op = $referer;
208
209 } elsif ( $op eq 'add_biblio' ) {
210     $shelfnumber = $query->param('shelfnumber');
211     $shelf = Koha::Virtualshelves->find($shelfnumber);
212     if ($shelf) {
213         if( my $barcode = $query->param('barcode') ) {
214             my $item = Koha::Items->find({ barcode => $barcode });
215             if ( $item ) {
216                 if ( $shelf->can_biblios_be_added( $loggedinuser ) ) {
217                     my $added = eval { $shelf->add_biblio( $item->biblionumber, $loggedinuser ); };
218                     if ($@) {
219                         push @messages, { type => 'error', code => ref($@), msg => $@ };
220                     } elsif ( $added ) {
221                         push @messages, { type => 'message', code => 'success_on_add_biblio' };
222                     } else {
223                         push @messages, { type => 'message', code => 'error_on_add_biblio' };
224                     }
225                 } else {
226                     push @messages, { type => 'error', code => 'unauthorized_on_add_biblio' };
227                 }
228             } else {
229                 push @messages, { type => 'error', code => 'item_does_not_exist' };
230             }
231         }
232     } else {
233         push @messages, { type => 'error', code => 'does_not_exist' };
234     }
235     $op = $referer;
236 } elsif ( $op eq 'remove_biblios' ) {
237     $shelfnumber = $query->param('shelfnumber');
238     $shelf = Koha::Virtualshelves->find($shelfnumber);
239     my @biblionumber = $query->multi_param('biblionumber');
240     if ($shelf) {
241         if ( $shelf->can_biblios_be_removed( $loggedinuser ) ) {
242             my $number_of_biblios_removed = eval {
243                 $shelf->remove_biblios(
244                     {
245                         biblionumbers => \@biblionumber,
246                         borrowernumber => $loggedinuser,
247                     }
248                 );
249             };
250             if ($@) {
251                 push @messages, { type => 'error', code => ref($@), msg => $@ };
252             } elsif ( $number_of_biblios_removed ) {
253                 push @messages, { type => 'message', code => 'success_on_remove_biblios' };
254             } else {
255                 push @messages, { type => 'error', code => 'no_biblio_removed' };
256             }
257         } else {
258             push @messages, { type => 'error', code => 'unauthorized_on_remove_biblios' };
259         }
260     } else {
261         push @messages, { type => 'error', code => 'does_not_exist' };
262     }
263     $op = 'view';
264 } elsif( $op eq 'transfer' ) {
265     $shelfnumber = $query->param('shelfnumber');
266     $shelf = Koha::Virtualshelves->find($shelfnumber) if $shelfnumber;
267     my $new_owner = $query->param('new_owner'); # borrowernumber or undef
268     my $error_code = $shelf
269         ? $shelf->cannot_be_transferred({ by => $loggedinuser, to => $new_owner, interface => 'opac' })
270         : 'does_not_exist';
271
272     if( !$new_owner && $error_code eq 'missing_to_parameter' ) { # show transfer form
273         my $patrons = [];
274         my $shares = $shelf->get_shares->search({ borrowernumber => { '!=' => undef } });
275         while( my $share = $shares->next ) {
276             my $email = $share->sharee->notice_email_address;
277             push @$patrons, { email => $email, borrowernumber => $share->get_column('borrowernumber') } if $email;
278         }
279         if( @$patrons ) {
280             $template->param( shared_users => $patrons );
281             $op = 'transfer';
282         } else {
283             push @messages, { type => 'error', code => 'no_email_found' };
284         }
285     } elsif( $error_code ) {
286         push @messages, { type => 'error', code => $error_code };
287         $op = 'list';
288     } else { # transfer; remove new_owner from virtualshelfshares, add loggedinuser
289         $shelf->_result->result_source->schema->txn_do( sub {
290             $shelf->get_shares->search({ borrowernumber => $new_owner })->delete;
291             Koha::Virtualshelfshare->new({ shelfnumber => $shelfnumber, borrowernumber => $loggedinuser, sharedate => dt_from_string })->store;
292             $shelf->owner($new_owner)->store;
293         });
294         $op = 'list';
295     }
296 }
297
298 # PART 2: After a possible action, view one list or show a number of lists
299 if ( $op eq 'view' ) {
300     $shelfnumber ||= $query->param('shelfnumber');
301     $shelf = Koha::Virtualshelves->find($shelfnumber);
302     if ( $shelf ) {
303         if ( $shelf->can_be_viewed( $loggedinuser ) ) {
304             $public = $shelf->public;
305
306             # Sortfield param may still include sort order with :asc or :desc, but direction overrides it
307             my( $sortfield, $direction );
308             if( $query->param('sortfield') ){
309                 ( $sortfield, $direction ) = split /:/, $query->param('sortfield');
310             } else {
311                 $sortfield = $shelf->sortfield;
312                 $direction = 'asc';
313             }
314             $direction = $query->param('direction') if $query->param('direction');
315             $direction = 'asc' if !$direction or ( $direction ne 'asc' and $direction ne 'desc' );
316             $sortfield = 'title' if !$sortfield or !grep { $_ eq $sortfield } qw( title author copyrightdate itemcallnumber dateadded );
317
318             my ( $page, $rows );
319             unless ( $query->param('print') or $query->param('rss') ) {
320                 $rows = C4::Context->preference('OPACnumSearchResults') || 20;
321                 $page = ( $query->param('page') ? $query->param('page') : 1 );
322             }
323             my $order_by = $sortfield eq 'itemcallnumber' ? 'items.cn_sort' : $sortfield;
324             my $contents = $shelf->get_contents->search(
325                 {},
326                 {
327                     distinct => 'biblionumber',
328                     join     => [ { 'biblionumber' => { 'biblioitems' => 'items' } } ],
329                     page     => $page,
330                     rows     => $rows,
331                     order_by => { "-$direction" => $order_by },
332                 }
333             );
334
335             # get biblionumbers stored in the cart
336             my @cart_list;
337             if(my $cart_list = $query->cookie('bib_list')){
338                 @cart_list = split(/\//, $cart_list);
339             }
340
341             my $patron = Koha::Patrons->find( $loggedinuser );
342
343             my $categorycode; # needed for may_article_request
344             if( C4::Context->preference('ArticleRequests') ) {
345                 $categorycode = $patron ? $patron->categorycode : undef;
346             }
347
348             my $record_processor = Koha::RecordProcessor->new({ filters => 'ViewPolicy' });
349
350             my $art_req_itypes;
351             if( C4::Context->preference('ArticleRequests') ) {
352                 $art_req_itypes = Koha::CirculationRules->guess_article_requestable_itemtypes({ $patron ? ( categorycode => $patron->categorycode ) : () });
353             }
354
355             my @items_info;
356             while ( my $content = $contents->next ) {
357                 my $biblionumber = $content->biblionumber;
358                 my $this_item    = GetBiblioData($biblionumber);
359                 my $biblio       = Koha::Biblios->find($biblionumber);
360                 my $record       = $biblio->metadata->record;
361                 my $framework    = GetFrameworkCode($biblionumber);
362                 $record_processor->options(
363                     {
364                     interface => 'opac',
365                     frameworkcode => $framework
366                 });
367                 $record_processor->process($record);
368
369                 my $marcflavour = C4::Context->preference("marcflavour");
370                 my $itemtype = Koha::Biblioitems->search({ biblionumber => $content->biblionumber })->next->itemtype;
371                 $itemtype = Koha::ItemTypes->find( $itemtype );
372                 if( $itemtype ) {
373                     $this_item->{imageurl}          = C4::Koha::getitemtypeimagelocation( 'opac', $itemtype->imageurl );
374                     $this_item->{description}       = $itemtype->description; #FIXME Should not it be translated_description?
375                     $this_item->{notforloan}        = $itemtype->notforloan;
376                 }
377                 $this_item->{'coins'}           = $biblio->get_coins;
378                 $this_item->{'normalized_upc'}  = GetNormalizedUPC( $record, $marcflavour );
379                 $this_item->{'normalized_ean'}  = GetNormalizedEAN( $record, $marcflavour );
380                 $this_item->{'normalized_oclc'} = GetNormalizedOCLCNumber( $record, $marcflavour );
381                 $this_item->{'normalized_isbn'} = GetNormalizedISBN( undef, $record, $marcflavour );
382                 # BZ17530: 'Intelligent' guess if result can be article requested
383                 $this_item->{artreqpossible} = ( $art_req_itypes->{ $this_item->{itemtype} // q{} } || $art_req_itypes->{ '*' } ) ? 1 : q{};
384
385                 unless ( defined $this_item->{size} ) {
386
387                     #TT has problems with size
388                     $this_item->{size} = q||;
389                 }
390
391                 if (C4::Context->preference('TagsEnabled') and C4::Context->preference('TagsShowOnList')) {
392                     $this_item->{TagLoop} = get_tags({
393                         biblionumber => $biblionumber, approved=>1, 'sort'=>'-weight',
394                         limit => C4::Context->preference('TagsShowOnList'),
395                     });
396                 }
397
398                 my $items = $biblio->items->filter_by_visible_in_opac({ patron => $patron });
399                 my $allow_onshelf_holds;
400                 while ( my $item = $items->next ) {
401
402                     # This method must take a Koha::Items rs
403                     $allow_onshelf_holds ||= Koha::CirculationRules->get_onshelfholds_policy(
404                         { item => $item, patron => $patron } );
405
406                 }
407
408                 $this_item->{allow_onshelf_holds} = $allow_onshelf_holds;
409                 $this_item->{'ITEM_RESULTS'} = $items;
410
411                 my $variables = {
412                     anonymous_session => ($loggedinuser) ? 0 : 1
413                 };
414                 $this_item->{XSLTBloc} = XSLTParse4Display(
415                     {
416                         biblionumber   => $biblionumber,
417                         record         => $record,
418                         xsl_syspref    => "OPACXSLTListsDisplay",
419                         fix_amps       => 1,
420                         xslt_variables => $variables,
421                         items_rs       => $items->reset,
422                     }
423                 );
424
425
426                 if ( grep {$_ eq $biblionumber} @cart_list) {
427                     $this_item->{incart} = 1;
428                 }
429
430                 $this_item->{biblio_object} = $biblio;
431                 $this_item->{biblionumber}  = $biblionumber;
432                 $this_item->{shelves} =
433                   Koha::Virtualshelves->get_shelves_containing_record(
434                     {
435                         biblionumber   => $biblionumber,
436                         borrowernumber => $loggedinuser,
437                     }
438                   );
439                 push @items_info, $this_item;
440             }
441
442             $template->param(
443                 can_manage_shelf   => $shelf->can_be_managed($loggedinuser),
444                 can_delete_shelf   => $shelf->can_be_deleted($loggedinuser),
445                 can_remove_biblios => $shelf->can_biblios_be_removed($loggedinuser),
446                 can_add_biblios    => $shelf->can_biblios_be_added($loggedinuser),
447                 itemsloop          => \@items_info,
448                 sortfield          => $sortfield,
449                 direction          => $direction,
450                 csv_profiles => Koha::CsvProfiles->search(
451                     {
452                         type       => 'marc',
453                         used_for   => 'export_records',
454                         staff_only => 0
455                     }
456                   ),
457             );
458             if ( $page ) {
459                 my $pager = $contents->pager;
460                 $template->param(
461                     pagination_bar => pagination_bar(
462                         q||, $pager->last_page - $pager->first_page + 1,
463                         $page, "page", { op => 'view', shelfnumber => $shelf->shelfnumber, sortfield => $sortfield, direction => $direction, }
464                     ),
465                 );
466             }
467         } else {
468             push @messages, { type => 'error', code => 'unauthorized_on_view' };
469             undef $shelf;
470         }
471     } else {
472         push @messages, { type => 'error', code => 'does_not_exist' };
473     }
474 } elsif ( $op eq 'list' ) {
475     my $shelves;
476     my ( $page, $rows ) = ( $query->param('page') || 1, 20 );
477     if ( !$public ) {
478         $shelves = Koha::Virtualshelves->get_private_shelves({ page => $page, rows => $rows, borrowernumber => $loggedinuser, });
479     } else {
480         $shelves = Koha::Virtualshelves->get_public_shelves({ page => $page, rows => $rows, });
481     }
482
483     my $pager = $shelves->pager;
484     $template->param(
485         shelves => $shelves,
486         pagination_bar => pagination_bar(
487             q||, $pager->last_page - $pager->first_page + 1,
488             $page, "page", { op => 'list', public => $public, }
489         ),
490     );
491 }
492
493 my ($staffuser, $permitteduser);
494 $staffuser = Koha::Patrons->find( $loggedinuser )->can_patron_change_staff_only_lists if $loggedinuser;
495 $permitteduser = Koha::Patrons->find( $loggedinuser )->can_patron_change_permitted_staff_lists if $loggedinuser;
496
497 $template->param(
498     op            => $op,
499     referer       => $referer,
500     shelf         => $shelf,
501     messages      => \@messages,
502     public        => $public,
503     print         => scalar $query->param('print') || 0,
504     listsview     => 1,
505     staffuser     => $staffuser,
506     permitteduser => $permitteduser
507 );
508
509 my $content_type = $query->param('rss')? 'rss' : 'html';
510 output_with_http_headers $query, $cookie, $template->output, $content_type;