Bug 13419: Add server-side processing for lists
[koha.git] / C4 / VirtualShelves / Page.pm
1 package C4::VirtualShelves::Page;
2
3 #
4 # Copyright 2000-2002 Katipo Communications
5 #
6 # This file is part of Koha.
7 #
8 # Koha is free software; you can redistribute it and/or modify it
9 # under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # Koha is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with Koha; if not, see <http://www.gnu.org/licenses>.
20
21 # perldoc at the end of the file, per convention.
22
23 use strict;
24 use warnings;
25
26 use CGI qw ( -utf8 );
27 use Exporter;
28 use Data::Dumper;
29
30 use C4::VirtualShelves qw/:DEFAULT ShelvesMax/;
31 use C4::Biblio;
32 use C4::Items;
33 use C4::Reserves;
34 use C4::Koha;
35 use C4::Auth qw/get_session/;
36 use C4::Members;
37 use C4::Output;
38 use C4::Dates qw/format_date/;
39 use C4::Tags qw(get_tags);
40 use C4::Csv;
41 use C4::XSLT;
42
43 use constant VIRTUALSHELVES_COUNT => 20;
44
45 use vars qw($debug @EXPORT @ISA $VERSION);
46
47 BEGIN {
48     $VERSION = 3.07.00.049;
49     @ISA     = qw(Exporter);
50     @EXPORT  = qw(&shelfpage);
51     $debug   = $ENV{DEBUG} || 0;
52 }
53
54 our %pages = (
55     intranet => { redirect => '/cgi-bin/koha/virtualshelves/shelves.pl', },
56     opac     => { redirect => '/cgi-bin/koha/opac-shelves.pl', },
57 );
58
59 sub shelfpage {
60     my ( $type, $query, $template, $loggedinuser, $cookie ) = @_;
61     ( $pages{$type} ) or $type = 'opac';
62     $query            or die "No query";
63     $template         or die "No template";
64     $template->param(
65     loggedinuser => $loggedinuser,
66     OpacAllowPublicListCreation => C4::Context->preference('OpacAllowPublicListCreation'),
67     );
68     my $edit;
69     my $shelves;
70     my @paramsloop;
71     my $totitems;
72     my $shelfoff    = ( $query->param('shelfoff') ? $query->param('shelfoff') : 1 );
73     $template->{VARS}->{'shelfoff'} = $shelfoff;
74     my $itemoff     = ( $query->param('itemoff')  ? $query->param('itemoff')  : 1 );
75     my $displaymode = ( $query->param('display')  ? $query->param('display')  : 'publicshelves' );
76     my ( $shelflimit, $shelfoffset, $shelveslimit, $shelvesoffset );
77     my $marcflavour = C4::Context->preference("marcflavour");
78
79     $shelflimit = ( $type eq 'opac' ? C4::Context->preference('OPACnumSearchResults') : C4::Context->preference('numSearchResults') );
80     $shelflimit = $shelflimit || ShelvesMax('MGRPAGE');
81     $shelfoffset   = ( $itemoff - 1 ) * $shelflimit;     # Sets the offset to begin retrieving items at
82     $shelveslimit  = $shelflimit;                        # Limits number of shelves returned for a given query (row_count)
83     $shelvesoffset = ( $shelfoff - 1 ) * $shelflimit;    # Sets the offset to begin retrieving shelves at (offset)
84                                                 # getting the Shelves list
85     my $category = ( ( $displaymode eq 'privateshelves' ) ? 1 : 2 );
86     my $shelflist = GetShelves( $category, $shelveslimit, $shelvesoffset, $loggedinuser );
87     my $totshelves = C4::VirtualShelves::GetShelfCount( $loggedinuser, $category );
88
89     my $op = $query->param('op');
90
91     # the format of this is unindented for ease of diff comparison to the old script
92     # Note: do not mistake the assignment statements below for comparisons!
93     if ( $query->param('modifyshelfcontents') ) {
94         my ( $shelfnumber, $barcode, $item, $biblio );
95         if ( $shelfnumber = $query->param('viewshelf') ) {
96             #add to shelf
97             if($barcode = $query->param('addbarcode') ) {
98                 if(ShelfPossibleAction( $loggedinuser, $shelfnumber, 'add')) {
99                     $item = GetItem( 0, $barcode);
100                     if (defined $item && $item->{'itemnumber'}) {
101                         $biblio = GetBiblioFromItemNumber( $item->{'itemnumber'} );
102                         AddToShelf( $biblio->{'biblionumber'}, $shelfnumber, $loggedinuser)
103                           or push @paramsloop, { duplicatebiblio => $barcode };
104                     }
105                     else {
106                         push @paramsloop, { failgetitem => $barcode };
107                     }
108                 }
109                 else {
110                     push @paramsloop, { nopermission => $shelfnumber };
111                 }
112             }
113             elsif(grep { /REM-(\d+)/ } $query->param) {
114             #remove item(s) from shelf
115                 if(ShelfPossibleAction($loggedinuser, $shelfnumber, 'delete')) {
116                 #This is just a general okay; DelFromShelf checks further
117                     my @bib;
118                     foreach($query->param) {
119                         /REM-(\d+)/ or next;
120                         push @bib, $1; #$1 is biblionumber
121                     }
122                     my $t= DelFromShelf(\@bib, $shelfnumber, $loggedinuser);
123                     if($t==0) {
124                         push @paramsloop, {nothingdeleted => $shelfnumber};
125                     }
126                     elsif($t<@bib) {
127                         push @paramsloop, {somedeleted => $shelfnumber};
128                     }
129                 }
130                 else {
131                     push @paramsloop, { nopermission => $shelfnumber };
132                 }
133             }
134         }
135         else {
136             push @paramsloop, { noshelfnumber => 1 };
137         }
138     }
139
140     my $showadd = 1;
141
142     # set the default tab, etc. (for OPAC)
143     my $shelf_type = ( $query->param('display') ? $query->param('display') : 'publicshelves' );
144     if ( defined $shelf_type ) {
145         if ( $shelf_type eq 'privateshelves' ) {
146             $template->param( showprivateshelves => 1 );
147         } elsif ( $shelf_type eq 'publicshelves' ) {
148             $template->param( showpublicshelves => 1 );
149             $showadd = 0;
150         } else {
151             $debug and warn "Invalid 'display' param ($shelf_type)";
152         }
153     } elsif ( $loggedinuser == -1 ) {
154         $template->param( showpublicshelves => 1 );
155     } else {
156         $template->param( showprivateshelves => 1 );
157     }
158
159     my ( $okmanage, $okview );
160     my $shelfnumber = $query->param('shelfnumber') || $query->param('viewshelf');
161     if ($shelfnumber) {
162         $okmanage = ShelfPossibleAction( $loggedinuser, $shelfnumber, 'manage' );
163         $okview   = ShelfPossibleAction( $loggedinuser, $shelfnumber, 'view' );
164     }
165
166     my $delflag = 0;
167
168   SWITCH: {
169         if ($op) {
170         #Saving modified shelf
171             if ( $op eq 'modifsave' ) {
172                 unless ($okmanage) {
173                         push @paramsloop, { nopermission => $shelfnumber };
174                         last SWITCH;
175                 }
176                 my $shelf = {
177                     shelfname          => $query->param('shelfname'),
178                     sortfield          => $query->param('sortfield'),
179                     allow_add          => $query->param('allow_add'),
180                     allow_delete_own   => $query->param('allow_delete_own'),
181                     allow_delete_other => $query->param('allow_delete_other'),
182                 };
183                 if($query->param('category')) { #optional
184                     $shelf->{category}= $query->param('category');
185                 }
186                 unless(ModShelf($shelfnumber, $shelf )) {
187                   push @paramsloop, {modifyfailure => $shelf->{shelfname}};
188                   last SWITCH;
189                 }
190
191                 if($displaymode eq "viewshelf"){
192                     print $query->redirect( $pages{$type}->{redirect} . "?viewshelf=$shelfnumber" );
193                 } elsif($displaymode eq "publicshelves"){
194                     print $query->redirect( $pages{$type}->{redirect} );
195                 } else {
196                     print $query->redirect( $pages{$type}->{redirect} . "?display=privateshelves" );
197                 }
198                 exit;
199             }
200         #Editing a shelf
201         elsif ( $op eq 'modif' ) {
202                 my ( $shelfnumber2, $shelfname, $owner, $category, $sortfield, $allow_add, $allow_delete_own, $allow_delete_other) = GetShelf($shelfnumber);
203                 my $member = GetMember( 'borrowernumber' => $owner );
204                 my $ownername = defined($member) ? $member->{firstname} . " " . $member->{surname} : '';
205                 $edit = 1;
206                 $template->param(
207                     edit                => 1,
208                     display             => $displaymode,
209                     shelfnumber         => $shelfnumber2,
210                     shelfname           => $shelfname,
211                     owner               => $owner,
212                     ownername           => $ownername,
213                     "category$category" => 1,
214                     category            => $category,
215                     sortfield           => $sortfield,
216                     allow_add           => $allow_add,
217                     allow_delete_own    => $allow_delete_own,
218                     allow_delete_other  => $allow_delete_other,
219                 );
220             }
221             last SWITCH;
222         }
223
224         #View a shelf
225         if ( $shelfnumber = $query->param('viewshelf') ) {
226             # explicitly fetch this shelf
227             my ($shelfnumber2,$shelfname,$owner,$category,$sorton) = GetShelf($shelfnumber);
228
229             $template->param(
230                 'DisplayMultiPlaceHold' => C4::Context->preference('DisplayMultiPlaceHold'),
231             );
232             if (C4::Context->preference('TagsEnabled')) {
233                 $template->param(TagsEnabled => 1);
234                     foreach (qw(TagsShowOnList TagsInputOnList)) {
235                     C4::Context->preference($_) and $template->param($_ => 1);
236                 }
237             }
238             #check that the user can view the shelf
239             if ( ShelfPossibleAction( $loggedinuser, $shelfnumber, 'view' ) ) {
240                 my $items;
241                 my $tag_quantity;
242                 my $sortfield = ( $sorton ? $sorton : 'title' );
243                 $sortfield = $query->param('sort') || $sortfield; ## Passed in sorting overrides default sorting
244                 my $direction = $query->param('direction') || 'asc';
245                 $template->param(
246                     sort      => $sortfield,
247                     direction => $direction,
248                 );
249                 ( $items, $totitems ) = GetShelfContents( $shelfnumber, $shelflimit, $shelfoffset, $sortfield, $direction );
250
251                 # get biblionumbers stored in the cart
252                 # Note that it's not use at the intranet
253                 my @cart_list;
254                 my $cart_cookie = ( $type eq 'opac' ? "bib_list" : "intranet_bib_list" );
255                 if($query->cookie($cart_cookie)){
256                     my $cart_list = $query->cookie($cart_cookie);
257                     @cart_list = split(/\//, $cart_list);
258                 }
259
260                 my $borrower = GetMember( 'borrowernumber' => $loggedinuser );
261
262                 for my $this_item (@$items) {
263                     my $biblionumber = $this_item->{'biblionumber'};
264                     my $record = GetMarcBiblio($biblionumber);
265                     if (C4::Context->preference("OPACXSLTResultsDisplay") && $type eq 'opac') {
266                         $this_item->{XSLTBloc} = XSLTParse4Display($biblionumber, $record, "OPACXSLTResultsDisplay");
267                     } elsif (C4::Context->preference("XSLTResultsDisplay") && $type eq 'intranet') {
268                         $this_item->{XSLTBloc} = XSLTParse4Display($biblionumber, $record, "XSLTResultsDisplay");
269                     }
270
271                     # the virtualshelfcontents table does not store these columns nor are they retrieved from the items
272                     # and itemtypes tables, so I'm commenting them out for now to quiet the log -crn
273                     #$this_item->{imageurl} = $imgdir."/".$itemtypes->{ $this_item->{itemtype}  }->{'imageurl'};
274                     #$this_item->{'description'} = $itemtypes->{ $this_item->{itemtype} }->{'description'};
275                     $this_item->{'dateadded'} = format_date( $this_item->{'dateadded'} );
276                     $this_item->{'imageurl'}  = getitemtypeinfo( $this_item->{'itemtype'}, $type )->{'imageurl'};
277                     $this_item->{'coins'}     = GetCOinSBiblio( $record );
278                     $this_item->{'subtitle'} = GetRecordValue('subtitle', $record, GetFrameworkCode($this_item->{'biblionumber'}));
279                     $this_item->{'normalized_upc'}  = GetNormalizedUPC(       $record,$marcflavour);
280                     $this_item->{'normalized_ean'}  = GetNormalizedEAN(       $record,$marcflavour);
281                     $this_item->{'normalized_oclc'} = GetNormalizedOCLCNumber($record,$marcflavour);
282                     $this_item->{'normalized_isbn'} = GetNormalizedISBN(undef,$record,$marcflavour);
283                     if(!defined($this_item->{'size'})) { $this_item->{'size'} = "" }; #TT has problems with size
284                     # Getting items infos for location display
285                     my @items_infos = &GetItemsLocationInfo( $this_item->{'biblionumber'});
286                     $this_item->{'itemsissued'} = CountItemsIssued( $this_item->{'biblionumber'} );
287                     $this_item->{'ITEM_RESULTS'} = \@items_infos;
288                     if ( grep {$_ eq $biblionumber} @cart_list) {
289                         $this_item->{'incart'} = 1;
290                     }
291
292                     if (C4::Context->preference('TagsEnabled') and $tag_quantity = C4::Context->preference('TagsShowOnList')) {
293                         $this_item->{'TagLoop'} = get_tags({
294                             biblionumber=>$this_item->{'biblionumber'}, approved=>1, 'sort'=>'-weight',
295                             limit=>$tag_quantity
296                             });
297                     }
298
299                     $this_item->{'allow_onshelf_holds'} = C4::Reserves::OnShelfHoldsAllowed($this_item, $borrower);
300                 }
301                 if($type eq 'intranet'){
302                     # Build drop-down list for 'Add To:' menu...
303                     my ($totalref, $pubshelves, $barshelves)=
304                     C4::VirtualShelves::GetSomeShelfNames($loggedinuser,'COMBO',1);
305                     $template->param(
306                         addbarshelves     => $totalref->{bartotal},
307                         addbarshelvesloop => $barshelves,
308                         addpubshelves     => $totalref->{pubtotal},
309                         addpubshelvesloop => $pubshelves,
310                     );
311                 }
312                 push @paramsloop, { display => 'privateshelves' } if $category == 1;
313                 $showadd = 1;
314                 my $i = 0;
315                 my $manageshelf = ShelfPossibleAction( $loggedinuser, $shelfnumber, 'manage' );
316                 my $can_delete_shelf = ShelfPossibleAction( $loggedinuser, $shelfnumber, 'delete_shelf' );
317                 $template->param(
318                     shelfname           => $shelfname,
319                     shelfnumber         => $shelfnumber,
320                     viewshelf           => $shelfnumber,
321                     sortfield           => $sortfield,
322                     manageshelf         => $manageshelf,
323                     allowremovingitems  => ShelfPossibleAction( $loggedinuser, $shelfnumber, 'delete'),
324                     allowaddingitem     => ShelfPossibleAction( $loggedinuser, $shelfnumber, 'add'),
325                     allowdeletingshelf  => $can_delete_shelf,
326                     "category$category" => 1,
327                     category            => $category,
328                     itemsloop           => $items,
329                     showprivateshelves  => $category==1,
330                 );
331             } else {
332                 push @paramsloop, { nopermission => $shelfnumber };
333             }
334             last SWITCH;
335         }
336
337         if ( $query->param('shelves') ) {
338             my $stay = 1;
339
340         #Add a shelf
341             if ( my $newshelf = $query->param('addshelf') ) {
342
343                 # note: a user can always add a new shelf (except database administrator account)
344                 my $shelfnumber = AddShelf( {
345                     shelfname => $newshelf,
346                     sortfield => $query->param('sortfield'),
347                     category => $query->param('category'),
348                     allow_add => $query->param('allow_add'),
349                     allow_delete_own => $query->param('allow_delete_own'),
350                     allow_delete_other => $query->param('allow_delete_other'),
351                     },
352                     $query->param('owner') );
353                 $stay = 1;
354                 if( !$shelfnumber ) {
355                     push @paramsloop, { addshelf_failed => 1 };
356                 } elsif ( $shelfnumber == -1 ) {    #shelf already exists.
357                     $showadd = 1;
358                     push @paramsloop, { already => $newshelf };
359                     $template->param( shelfnumber => $shelfnumber );
360                 } else {
361                     print $query->redirect( $pages{$type}->{redirect} . "?viewshelf=$shelfnumber" );
362                     exit;
363                 }
364             }
365
366         #Deleting a shelf (asking for confirmation if it has entries)
367             foreach ( $query->param() ) {
368                 /(DEL|REMSHR)-(\d+)/ or next;
369                 $delflag = 1;
370                 my $number = $2;
371                 unless ( defined $shelflist->{$number} ) {
372                     push( @paramsloop, { unrecognized => $number } );
373                     last;
374                 }
375                 #remove a share
376                 if(/REMSHR/) {
377                     RemoveShare($loggedinuser, $number);
378                     delete $shelflist->{$number} if exists $shelflist->{$number};
379                     $stay=0;
380                     next;
381                 }
382
383                 my $can_manage = ShelfPossibleAction( $loggedinuser, $number, 'manage' );
384                 my $can_delete = ShelfPossibleAction( $loggedinuser, $number, 'delete_shelf' );
385                 unless ( $can_manage or $can_delete ) {
386                     push( @paramsloop, { nopermission => $shelfnumber } );
387                     last;
388                 }
389                 my $contents;
390                 ( $contents, $totshelves ) = GetShelfContents( $number, $shelveslimit, $shelvesoffset );
391                 if ( $totshelves > 0 ) {
392                     unless ( scalar grep { /^CONFIRM-$number$/ } $query->param() ) {
393                         if ( defined $shelflist->{$number} ) {
394                             push( @paramsloop, { need_confirm => $shelflist->{$number}->{shelfname}, count => $totshelves, single => ($totshelves eq 1 ? 1:0) } );
395                             $shelflist->{$number}->{confirm} = $number;
396                         }
397                         $stay = 0;
398                         next;
399                     }
400                 }
401                 my $name;
402                 if ( defined $shelflist->{$number} ) {
403                     $name = $shelflist->{$number}->{'shelfname'};
404                     delete $shelflist->{$number};
405                 }
406                 unless ( DelShelf($number) ) {
407                     push( @paramsloop, { delete_fail => $name } );
408                     last;
409                 }
410                 push( @paramsloop, { delete_ok => $name } );
411
412                 $stay = 0;
413             }
414             $showadd = 1;
415             if ($stay){
416                 $template->param( shelves => 1 );
417                 $shelves = 1;
418             }
419             last SWITCH;
420         }
421     } # end of SWITCH block
422
423     (@paramsloop) and $template->param( paramsloop => \@paramsloop );
424     $showadd      and $template->param( showadd    => 1 );
425     my @shelvesloop;
426     my @shelveslooppriv;
427     my $numberCanManage = 0;
428
429     # rebuild shelflist in case a shelf has been added
430     $shelflist = GetShelves( $category, $shelveslimit, $shelvesoffset, $loggedinuser ) unless $delflag;
431     $totshelves = C4::VirtualShelves::GetShelfCount( $loggedinuser, $category ) unless $delflag;
432     foreach my $element ( sort { lc( $shelflist->{$a}->{'shelfname'} ) cmp lc( $shelflist->{$b}->{'shelfname'} ) } keys %$shelflist ) {
433         my %line;
434         $shelflist->{$element}->{shelf} = $element;
435         my $category  = $shelflist->{$element}->{'category'};
436         my $owner     = $shelflist->{$element}->{'owner'}||0;
437         my $canmanage = ShelfPossibleAction( $loggedinuser, $element, 'manage' );
438         my $candelete = ShelfPossibleAction( $loggedinuser, $element, 'delete_shelf' );
439         $shelflist->{$element}->{"viewcategory$category"} = 1;
440         $shelflist->{$element}->{manageshelf} = $canmanage;
441         $shelflist->{$element}->{allowdeletingshelf} = $candelete;
442         if($canmanage || ($loggedinuser && $owner==$loggedinuser)) {
443             $shelflist->{$element}->{'mine'} = 1;
444         }
445         my $member = GetMember( 'borrowernumber' => $owner );
446         $shelflist->{$element}->{ownername} = defined($member) ? $member->{firstname} . " " . $member->{surname} : '';
447         $numberCanManage++ if $canmanage;    # possibly outmoded
448         if ( $shelflist->{$element}->{'category'} eq '1' ) {
449             $shelflist->{$element}->{shares} = IsSharedList($element);
450             push( @shelveslooppriv, $shelflist->{$element} );
451         } else {
452             push( @shelvesloop, $shelflist->{$element} );
453         }
454     }
455
456     my $url = $type eq 'opac' ? "/cgi-bin/koha/opac-shelves.pl" : "/cgi-bin/koha/virtualshelves/shelves.pl";
457     my %qhash = ();
458     foreach (qw(display viewshelf sortfield sort direction)) {
459         $qhash{$_} = $query->param($_) if $query->param($_);
460     }
461     ( scalar keys %qhash ) and $url .= '?' . join '&', map { "$_=$qhash{$_}" } keys %qhash;
462     if ( $shelfnumber && $totitems ) {
463         $template->param(  pagination_bar => pagination_bar( $url, ( int( $totitems / $shelflimit ) ) + ( ( $totitems % $shelflimit ) > 0 ? 1 : 0 ), $itemoff, "itemoff" )  );
464     } elsif ( $totshelves ) {
465         $template->param(
466              pagination_bar => pagination_bar( $url, ( int( $totshelves / $shelveslimit ) ) + ( ( $totshelves % $shelveslimit ) > 0 ? 1 : 0 ), $shelfoff, "shelfoff" )  );
467     }
468     $template->param(
469         shelveslooppriv                                                    => \@shelveslooppriv,
470         shelvesloop                                                        => \@shelvesloop,
471         shelvesloopall                                                     => [ ( @shelvesloop, @shelveslooppriv ) ],
472         numberCanManage                                                    => $numberCanManage,
473         "BiblioDefaultView" . C4::Context->preference("BiblioDefaultView") => 1,
474         csv_profiles                                                       => GetCsvProfilesLoop('marc')
475     );
476
477     unless( $shelfnumber or $shelves or $edit ) {
478         # Only used for intranet
479         $template->param( op => 'list' );
480     }
481
482     if ($shelves or    # note: this part looks duplicative, but is intentional
483         $edit
484       ) {
485         $template->param( seflag => 1 );
486         #This hack is just another argument for refactoring this script one day
487         #At this point you are adding or editing a list; if you add, then you add a private list (by default) with permissions as below; if you edit, do not pass these permissions, they must come from the database
488         $template->param( allow_add => 0, allow_delete_own => 1, allow_delete_other => 0) unless $shelfnumber;
489     }
490
491 #Next call updates the shelves for the Lists button.
492 #May not always be needed (when nothing changed), but doesn't take much.
493     my ($total, $pubshelves, $barshelves) = C4::VirtualShelves::GetSomeShelfNames($loggedinuser, 'MASTHEAD');
494     $template->param(
495             barshelves     => $total->{bartotal},
496             barshelvesloop => $barshelves,
497             pubshelves     => $total->{pubtotal},
498             pubshelvesloop => $pubshelves,
499     );
500
501     output_html_with_http_headers $query, $cookie, $template->output;
502 }
503
504 1;
505 __END__
506
507 =head1 NAME
508
509 VirtualShelves/Page.pm
510
511 =head1 DESCRIPTION
512
513 Module used for both OPAC and intranet pages.
514
515 =head1 CGI PARAMETERS
516
517 =over 4
518
519 =item C<modifyshelfcontents>
520
521 If this script has to modify the shelf content.
522
523 =item C<shelfnumber>
524
525 To know on which shelf to work.
526
527 =item C<addbarcode>
528
529 =item C<op>
530
531  Op can be:
532     * modif: show the template allowing modification of the shelves;
533     * modifsave: save changes from modif mode.
534
535 =item C<viewshelf>
536
537 Load template with 'viewshelves param' displaying the shelf's information.
538
539 =item C<shelves>
540
541 If the param shelves == 1, then add or delete a shelf.
542
543 =item C<addshelf>
544
545 If the param shelves == 1, then addshelf is the name of the shelf to add.
546
547 =back
548
549 =cut