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