15ee4da41233eb943fac1f6aa4347949ca6cd4a8
[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     my $error_code = $shelf
266         ? $shelf->cannot_be_transferred({ by => $loggedinuser, to => $new_owner, interface => 'opac' })
267         : 'does_not_exist';
268
269     if( !$new_owner && $error_code eq 'missing_to_parameter' ) { # show transfer form
270         my $patrons = [];
271         my $shares = $shelf->get_shares->search({ borrowernumber => { '!=' => undef } });
272         while( my $share = $shares->next ) {
273             my $email = $share->sharee->notice_email_address;
274             push @$patrons, { email => $email, borrowernumber => $share->get_column('borrowernumber') } if $email;
275         }
276         if( @$patrons ) {
277             $template->param( shared_users => $patrons );
278             $op = 'transfer';
279         } else {
280             push @messages, { type => 'error', code => 'no_email_found' };
281         }
282     } elsif( $error_code ) {
283         push @messages, { type => 'error', code => $error_code };
284         $op = 'list';
285     } else { # transfer; remove new_owner from virtualshelfshares, add loggedinuser
286         $shelf->_result->result_source->schema->txn_do( sub {
287             $shelf->get_shares->search({ borrowernumber => $new_owner })->delete;
288             Koha::Virtualshelfshare->new({ shelfnumber => $shelfnumber, borrowernumber => $loggedinuser, sharedate => dt_from_string })->store;
289             $shelf->owner($new_owner)->store;
290         });
291         $op = 'list';
292     }
293 }
294
295 # PART 2: After a possible action, view one list or show a number of lists
296 if ( $op eq 'view' ) {
297     $shelfnumber ||= $query->param('shelfnumber');
298     $shelf = Koha::Virtualshelves->find($shelfnumber);
299     if ( $shelf ) {
300         if ( $shelf->can_be_viewed( $loggedinuser ) ) {
301             $public = $shelf->public;
302
303             # Sortfield param may still include sort order with :asc or :desc, but direction overrides it
304             my( $sortfield, $direction );
305             if( $query->param('sortfield') ){
306                 ( $sortfield, $direction ) = split /:/, $query->param('sortfield');
307             } else {
308                 $sortfield = $shelf->sortfield;
309                 $direction = 'asc';
310             }
311             $direction = $query->param('direction') if $query->param('direction');
312             $direction = 'asc' if !$direction or ( $direction ne 'asc' and $direction ne 'desc' );
313             $sortfield = 'title' if !$sortfield or !grep { $_ eq $sortfield } qw( title author copyrightdate itemcallnumber dateadded );
314
315             my ( $page, $rows );
316             unless ( $query->param('print') or $query->param('rss') ) {
317                 $rows = C4::Context->preference('OPACnumSearchResults') || 20;
318                 $page = ( $query->param('page') ? $query->param('page') : 1 );
319             }
320             my $order_by = $sortfield eq 'itemcallnumber' ? 'items.cn_sort' : $sortfield;
321             my $contents = $shelf->get_contents->search(
322                 {},
323                 {
324                     distinct => 'biblionumber',
325                     join     => [ { 'biblionumber' => { 'biblioitems' => 'items' } } ],
326                     page     => $page,
327                     rows     => $rows,
328                     order_by => { "-$direction" => $order_by },
329                 }
330             );
331
332             # get biblionumbers stored in the cart
333             my @cart_list;
334             if(my $cart_list = $query->cookie('bib_list')){
335                 @cart_list = split(/\//, $cart_list);
336             }
337
338             my $patron = Koha::Patrons->find( $loggedinuser );
339
340             my $categorycode; # needed for may_article_request
341             if( C4::Context->preference('ArticleRequests') ) {
342                 $categorycode = $patron ? $patron->categorycode : undef;
343             }
344
345             my $record_processor = Koha::RecordProcessor->new({ filters => 'ViewPolicy' });
346
347             my $art_req_itypes;
348             if( C4::Context->preference('ArticleRequests') ) {
349                 $art_req_itypes = Koha::CirculationRules->guess_article_requestable_itemtypes({ $patron ? ( categorycode => $patron->categorycode ) : () });
350             }
351
352             my @items_info;
353             while ( my $content = $contents->next ) {
354                 my $biblionumber = $content->biblionumber;
355                 my $this_item    = GetBiblioData($biblionumber);
356                 my $record = GetMarcBiblio({ biblionumber => $biblionumber });
357                 my $framework = GetFrameworkCode( $biblionumber );
358                 my $biblio = Koha::Biblios->find( $biblionumber );
359                 $record_processor->options({
360                     interface => 'opac',
361                     frameworkcode => $framework
362                 });
363                 $record_processor->process($record);
364
365                 my $marcflavour = C4::Context->preference("marcflavour");
366                 my $itemtype = Koha::Biblioitems->search({ biblionumber => $content->biblionumber })->next->itemtype;
367                 $itemtype = Koha::ItemTypes->find( $itemtype );
368                 if( $itemtype ) {
369                     $this_item->{imageurl}          = C4::Koha::getitemtypeimagelocation( 'opac', $itemtype->imageurl );
370                     $this_item->{description}       = $itemtype->description; #FIXME Should not it be translated_description?
371                     $this_item->{notforloan}        = $itemtype->notforloan;
372                 }
373                 $this_item->{'coins'}           = $biblio->get_coins;
374                 $this_item->{'normalized_upc'}  = GetNormalizedUPC( $record, $marcflavour );
375                 $this_item->{'normalized_ean'}  = GetNormalizedEAN( $record, $marcflavour );
376                 $this_item->{'normalized_oclc'} = GetNormalizedOCLCNumber( $record, $marcflavour );
377                 $this_item->{'normalized_isbn'} = GetNormalizedISBN( undef, $record, $marcflavour );
378                 # BZ17530: 'Intelligent' guess if result can be article requested
379                 $this_item->{artreqpossible} = ( $art_req_itypes->{ $this_item->{itemtype} // q{} } || $art_req_itypes->{ '*' } ) ? 1 : q{};
380
381                 unless ( defined $this_item->{size} ) {
382
383                     #TT has problems with size
384                     $this_item->{size} = q||;
385                 }
386
387                 if (C4::Context->preference('TagsEnabled') and C4::Context->preference('TagsShowOnList')) {
388                     $this_item->{TagLoop} = get_tags({
389                         biblionumber => $biblionumber, approved=>1, 'sort'=>'-weight',
390                         limit => C4::Context->preference('TagsShowOnList'),
391                     });
392                 }
393
394                 my $items = $biblio->items->filter_by_visible_in_opac({ patron => $patron });
395                 my $allow_onshelf_holds;
396                 while ( my $item = $items->next ) {
397
398                     # This method must take a Koha::Items rs
399                     $allow_onshelf_holds ||= Koha::CirculationRules->get_onshelfholds_policy(
400                         { item => $item, patron => $patron } );
401
402                 }
403
404                 $this_item->{allow_onshelf_holds} = $allow_onshelf_holds;
405                 $this_item->{'ITEM_RESULTS'} = $items;
406
407                 my $variables = {
408                     anonymous_session => ($loggedinuser) ? 0 : 1
409                 };
410                 $this_item->{XSLTBloc} = XSLTParse4Display(
411                     {
412                         biblionumber   => $biblionumber,
413                         record         => $record,
414                         xsl_syspref    => "OPACXSLTListsDisplay",
415                         fix_amps       => 1,
416                         xslt_variables => $variables,
417                         items_rs       => $items->reset,
418                     }
419                 );
420
421
422                 if ( grep {$_ eq $biblionumber} @cart_list) {
423                     $this_item->{incart} = 1;
424                 }
425
426                 $this_item->{biblio_object} = $biblio;
427                 $this_item->{biblionumber}  = $biblionumber;
428                 push @items_info, $this_item;
429             }
430
431             $template->param(
432                 can_manage_shelf   => $shelf->can_be_managed($loggedinuser),
433                 can_delete_shelf   => $shelf->can_be_deleted($loggedinuser),
434                 can_remove_biblios => $shelf->can_biblios_be_removed($loggedinuser),
435                 can_add_biblios    => $shelf->can_biblios_be_added($loggedinuser),
436                 itemsloop          => \@items_info,
437                 sortfield          => $sortfield,
438                 direction          => $direction,
439                 csv_profiles => Koha::CsvProfiles->search(
440                     {
441                         type       => 'marc',
442                         used_for   => 'export_records',
443                         staff_only => 0
444                     }
445                   ),
446             );
447             if ( $page ) {
448                 my $pager = $contents->pager;
449                 $template->param(
450                     pagination_bar => pagination_bar(
451                         q||, $pager->last_page - $pager->first_page + 1,
452                         $page, "page", { op => 'view', shelfnumber => $shelf->shelfnumber, sortfield => $sortfield, direction => $direction, }
453                     ),
454                 );
455             }
456         } else {
457             push @messages, { type => 'error', code => 'unauthorized_on_view' };
458             undef $shelf;
459         }
460     } else {
461         push @messages, { type => 'error', code => 'does_not_exist' };
462     }
463 } elsif ( $op eq 'list' ) {
464     my $shelves;
465     my ( $page, $rows ) = ( $query->param('page') || 1, 20 );
466     if ( !$public ) {
467         $shelves = Koha::Virtualshelves->get_private_shelves({ page => $page, rows => $rows, borrowernumber => $loggedinuser, });
468     } else {
469         $shelves = Koha::Virtualshelves->get_public_shelves({ page => $page, rows => $rows, });
470     }
471
472     my $pager = $shelves->pager;
473     $template->param(
474         shelves => $shelves,
475         pagination_bar => pagination_bar(
476             q||, $pager->last_page - $pager->first_page + 1,
477             $page, "page", { op => 'list', public => $public, }
478         ),
479     );
480 }
481
482 my $staffuser;
483 $staffuser = Koha::Patrons->find( $loggedinuser )->can_patron_change_staff_only_lists if $loggedinuser;
484 $template->param(
485     op       => $op,
486     referer  => $referer,
487     shelf    => $shelf,
488     messages => \@messages,
489     public   => $public,
490     print    => scalar $query->param('print') || 0,
491     listsview => 1,
492     staffuser => $staffuser,
493 );
494
495 my $content_type = $query->param('rss')? 'rss' : 'html';
496 output_with_http_headers $query, $cookie, $template->output, $content_type;