Bug 16522: (follow-up) MARC display templates and get_marc_host fixes
[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
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 $biblio       = Koha::Biblios->find($biblionumber);
357                 my $record       = $biblio->metadata->record;
358                 my $framework    = GetFrameworkCode($biblionumber);
359                 $record_processor->options(
360                     {
361                     interface => 'opac',
362                     frameworkcode => $framework
363                 });
364                 $record_processor->process($record);
365
366                 my $marcflavour = C4::Context->preference("marcflavour");
367                 my $itemtype = Koha::Biblioitems->search({ biblionumber => $content->biblionumber })->next->itemtype;
368                 $itemtype = Koha::ItemTypes->find( $itemtype );
369                 if( $itemtype ) {
370                     $this_item->{imageurl}          = C4::Koha::getitemtypeimagelocation( 'opac', $itemtype->imageurl );
371                     $this_item->{description}       = $itemtype->description; #FIXME Should not it be translated_description?
372                     $this_item->{notforloan}        = $itemtype->notforloan;
373                 }
374                 $this_item->{'coins'}           = $biblio->get_coins;
375                 $this_item->{'normalized_upc'}  = GetNormalizedUPC( $record, $marcflavour );
376                 $this_item->{'normalized_ean'}  = GetNormalizedEAN( $record, $marcflavour );
377                 $this_item->{'normalized_oclc'} = GetNormalizedOCLCNumber( $record, $marcflavour );
378                 $this_item->{'normalized_isbn'} = GetNormalizedISBN( undef, $record, $marcflavour );
379                 # BZ17530: 'Intelligent' guess if result can be article requested
380                 $this_item->{artreqpossible} = ( $art_req_itypes->{ $this_item->{itemtype} // q{} } || $art_req_itypes->{ '*' } ) ? 1 : q{};
381
382                 unless ( defined $this_item->{size} ) {
383
384                     #TT has problems with size
385                     $this_item->{size} = q||;
386                 }
387
388                 if (C4::Context->preference('TagsEnabled') and C4::Context->preference('TagsShowOnList')) {
389                     $this_item->{TagLoop} = get_tags({
390                         biblionumber => $biblionumber, approved=>1, 'sort'=>'-weight',
391                         limit => C4::Context->preference('TagsShowOnList'),
392                     });
393                 }
394
395                 my $items = $biblio->items->filter_by_visible_in_opac({ patron => $patron });
396                 my $allow_onshelf_holds;
397                 while ( my $item = $items->next ) {
398
399                     # This method must take a Koha::Items rs
400                     $allow_onshelf_holds ||= Koha::CirculationRules->get_onshelfholds_policy(
401                         { item => $item, patron => $patron } );
402
403                 }
404
405                 $this_item->{allow_onshelf_holds} = $allow_onshelf_holds;
406                 $this_item->{'ITEM_RESULTS'} = $items;
407
408                 my $variables = {
409                     anonymous_session => ($loggedinuser) ? 0 : 1
410                 };
411                 $this_item->{XSLTBloc} = XSLTParse4Display(
412                     {
413                         biblionumber   => $biblionumber,
414                         record         => $record,
415                         xsl_syspref    => "OPACXSLTListsDisplay",
416                         fix_amps       => 1,
417                         xslt_variables => $variables,
418                         items_rs       => $items->reset,
419                     }
420                 );
421
422
423                 if ( grep {$_ eq $biblionumber} @cart_list) {
424                     $this_item->{incart} = 1;
425                 }
426
427                 $this_item->{biblio_object} = $biblio;
428                 $this_item->{biblionumber}  = $biblionumber;
429                 push @items_info, $this_item;
430             }
431
432             $template->param(
433                 can_manage_shelf   => $shelf->can_be_managed($loggedinuser),
434                 can_delete_shelf   => $shelf->can_be_deleted($loggedinuser),
435                 can_remove_biblios => $shelf->can_biblios_be_removed($loggedinuser),
436                 can_add_biblios    => $shelf->can_biblios_be_added($loggedinuser),
437                 itemsloop          => \@items_info,
438                 sortfield          => $sortfield,
439                 direction          => $direction,
440                 csv_profiles => Koha::CsvProfiles->search(
441                     {
442                         type       => 'marc',
443                         used_for   => 'export_records',
444                         staff_only => 0
445                     }
446                   ),
447             );
448             if ( $page ) {
449                 my $pager = $contents->pager;
450                 $template->param(
451                     pagination_bar => pagination_bar(
452                         q||, $pager->last_page - $pager->first_page + 1,
453                         $page, "page", { op => 'view', shelfnumber => $shelf->shelfnumber, sortfield => $sortfield, direction => $direction, }
454                     ),
455                 );
456             }
457         } else {
458             push @messages, { type => 'error', code => 'unauthorized_on_view' };
459             undef $shelf;
460         }
461     } else {
462         push @messages, { type => 'error', code => 'does_not_exist' };
463     }
464 } elsif ( $op eq 'list' ) {
465     my $shelves;
466     my ( $page, $rows ) = ( $query->param('page') || 1, 20 );
467     if ( !$public ) {
468         $shelves = Koha::Virtualshelves->get_private_shelves({ page => $page, rows => $rows, borrowernumber => $loggedinuser, });
469     } else {
470         $shelves = Koha::Virtualshelves->get_public_shelves({ page => $page, rows => $rows, });
471     }
472
473     my $pager = $shelves->pager;
474     $template->param(
475         shelves => $shelves,
476         pagination_bar => pagination_bar(
477             q||, $pager->last_page - $pager->first_page + 1,
478             $page, "page", { op => 'list', public => $public, }
479         ),
480     );
481 }
482
483 my $staffuser;
484 $staffuser = Koha::Patrons->find( $loggedinuser )->can_patron_change_staff_only_lists if $loggedinuser;
485 $template->param(
486     op       => $op,
487     referer  => $referer,
488     shelf    => $shelf,
489     messages => \@messages,
490     public   => $public,
491     print    => scalar $query->param('print') || 0,
492     listsview => 1,
493     staffuser => $staffuser,
494 );
495
496 my $content_type = $query->param('rss')? 'rss' : 'html';
497 output_with_http_headers $query, $cookie, $template->output, $content_type;