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