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