Bug 14544: Make the intranet side independent of Page.pm
[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 Koha::Virtualshelves;
44
45 use constant VIRTUALSHELVES_COUNT => 20;
46
47 use vars qw($debug @EXPORT @ISA $VERSION);
48
49 BEGIN {
50     $VERSION = 3.07.00.049;
51     @ISA     = qw(Exporter);
52     @EXPORT  = qw(&shelfpage);
53     $debug   = $ENV{DEBUG} || 0;
54 }
55
56 my @messages;
57 our %pages = (
58     intranet => { redirect => '/cgi-bin/koha/virtualshelves/shelves.pl', },
59     opac     => { redirect => '/cgi-bin/koha/opac-shelves.pl', },
60 );
61
62 sub shelfpage {
63     my ( $type, $query, $template, $loggedinuser, $cookie ) = @_;
64     ( $pages{$type} ) or $type = 'opac';
65     $query            or die "No query";
66     $template         or die "No template";
67     $template->param(
68     loggedinuser => $loggedinuser,
69     OpacAllowPublicListCreation => C4::Context->preference('OpacAllowPublicListCreation'),
70     );
71     my $shelves;
72     my @paramsloop;
73     my $totitems;
74     my $shelfoff    = ( $query->param('shelfoff') ? $query->param('shelfoff') : 1 );
75     $template->{VARS}->{'shelfoff'} = $shelfoff;
76     my $itemoff     = ( $query->param('itemoff')  ? $query->param('itemoff')  : 1 );
77     my $displaymode = ( $query->param('display')  ? $query->param('display')  : 'publicshelves' );
78     my ( $shelflimit, $shelfoffset, $shelveslimit, $shelvesoffset );
79     my $marcflavour = C4::Context->preference("marcflavour");
80
81     unless ( $query->param('print') ) {
82         $shelflimit = ( $type eq 'opac' ? C4::Context->preference('OPACnumSearchResults') : C4::Context->preference('numSearchResults') );
83         $shelflimit = $shelflimit || ShelvesMax('MGRPAGE');
84         $shelflimit = undef if $query->param('rss');
85         $shelfoffset   = ( $itemoff - 1 ) * $shelflimit;     # Sets the offset to begin retrieving items at
86         $shelveslimit  = $shelflimit;                        # Limits number of shelves returned for a given query (row_count)
87         $shelvesoffset = ( $shelfoff - 1 ) * $shelflimit;    # Sets the offset to begin retrieving shelves at (offset)
88     }
89
90     # getting the Shelves list
91     my $category = ( ( $displaymode eq 'privateshelves' ) ? 1 : 2 );
92     my $shelflist = GetShelves( $category, $shelveslimit, $shelvesoffset, $loggedinuser );
93     my $totshelves = C4::VirtualShelves::GetShelfCount( $loggedinuser, $category );
94
95     my $op = $query->param('op');
96
97     # the format of this is unindented for ease of diff comparison to the old script
98     # Note: do not mistake the assignment statements below for comparisons!
99     if ( $query->param('modifyshelfcontents') ) {
100         my ( $shelfnumber, $barcode, $item, $biblio );
101         if ( $shelfnumber = $query->param('viewshelf') ) {
102             #add to shelf
103             if($barcode = $query->param('addbarcode') ) {
104                 if(ShelfPossibleAction( $loggedinuser, $shelfnumber, 'add')) {
105                     $item = GetItem( 0, $barcode);
106                     if (defined $item && $item->{'itemnumber'}) {
107                         $biblio = GetBiblioFromItemNumber( $item->{'itemnumber'} );
108                         Koha::Virtualshelves->find( $shelfnumber )->add_biblio( $biblio->{biblionumber}, $loggedinuser )
109                           or push @paramsloop, { duplicatebiblio => $barcode };
110                     }
111                     else {
112                         push @paramsloop, { failgetitem => $barcode };
113                     }
114                 }
115                 else {
116                     push @paramsloop, { nopermission => $shelfnumber };
117                 }
118             }
119             elsif(grep { /REM-(\d+)/ } $query->param) {
120             #remove item(s) from shelf
121                 if(ShelfPossibleAction($loggedinuser, $shelfnumber, 'delete')) {
122                     my @bib;
123                     foreach($query->param) {
124                         /REM-(\d+)/ or next;
125                         push @bib, $1; #$1 is biblionumber
126                     }
127                     my $shelf = Koha::Virtualshelves->find( $shelfnumber );
128                     my $number_of_biblios_removed = $shelf->remove_biblios( { biblionumbers => \@bib, borrowernumber => $loggedinuser } );
129                     if( $number_of_biblios_removed == 0) {
130                         push @paramsloop, {nothingdeleted => $shelfnumber};
131                     }
132                     elsif( $number_of_biblios_removed < @bib ) {
133                         push @paramsloop, {somedeleted => $shelfnumber};
134                     }
135                 }
136                 else {
137                     push @paramsloop, { nopermission => $shelfnumber };
138                 }
139             }
140         }
141         else {
142             push @paramsloop, { noshelfnumber => 1 };
143         }
144     }
145
146     my $showadd = 1;
147
148     # set the default tab, etc. (for OPAC)
149     my $shelf_type = ( $query->param('display') ? $query->param('display') : 'publicshelves' );
150     if ( defined $shelf_type ) {
151         if ( $shelf_type eq 'privateshelves' ) {
152             $template->param( showprivateshelves => 1 );
153         } elsif ( $shelf_type eq 'publicshelves' ) {
154             $template->param( showpublicshelves => 1 );
155             $showadd = 0;
156         } else {
157             $debug and warn "Invalid 'display' param ($shelf_type)";
158         }
159     } elsif ( $loggedinuser == -1 ) {
160         $template->param( showpublicshelves => 1 );
161     } else {
162         $template->param( showprivateshelves => 1 );
163     }
164
165     my ( $okmanage, $okview );
166     my $shelfnumber = $query->param('shelfnumber') || $query->param('viewshelf');
167     if ($shelfnumber) {
168         $okmanage = ShelfPossibleAction( $loggedinuser, $shelfnumber, 'manage' );
169         $okview   = ShelfPossibleAction( $loggedinuser, $shelfnumber, 'view' );
170     }
171
172     my $delflag = 0;
173
174   SWITCH: {
175         if ($op) {
176         #Saving modified shelf
177             if ( $op eq 'modifsave' ) {
178                 unless ($okmanage) {
179                         push @paramsloop, { nopermission => $shelfnumber };
180                         last SWITCH;
181                 }
182                 my $shelf = Koha::Virtualshelves->find( $shelfnumber );
183                 $shelf->shelfname($query->param('shelfname'));
184                 $shelf->sortfield($query->param('sortfield'));
185                 $shelf->allow_add($query->param('allow_add'));
186                 $shelf->allow_delete_own($query->param('allow_delete_own'));
187                 $shelf->allow_delete_other($query->param('allow_delete_other'));
188                 if( my $category = $query->param('category')) { #optional
189                     $shelf->category($category);
190                 }
191                 eval { $shelf->store };
192                 if ( $@ ) {
193                   push @paramsloop, {modifyfailure => $shelf->{shelfname}};
194                   last SWITCH;
195                 }
196
197                 if($displaymode eq "viewshelf"){
198                     print $query->redirect( $pages{$type}->{redirect} . "?viewshelf=$shelfnumber" );
199                 } elsif($displaymode eq "publicshelves"){
200                     print $query->redirect( $pages{$type}->{redirect} );
201                 } else {
202                     print $query->redirect( $pages{$type}->{redirect} . "?display=privateshelves" );
203                 }
204                 exit;
205             }
206         #Editing a shelf
207         elsif ( $op eq 'modif' ) {
208                 my $shelf = Koha::Virtualshelves->find( $shelfnumber );
209                 my $member = GetMember( 'borrowernumber' => $shelf->owner );
210                 my $ownername = defined($member) ? $member->{firstname} . " " . $member->{surname} : '';
211                 $template->param(
212                     edit                => 1,
213                     display             => $displaymode,
214                     shelfnumber         => $shelf->shelfnumber,
215                     shelfname           => $shelf->shelfname,
216                     owner               => $shelf->owner,
217                     ownername           => $ownername,
218                     "category".$shelf->category => 1,
219                     category            => $shelf->category,
220                     sortfield           => $shelf->sortfield,
221                     allow_add           => $shelf->allow_add,
222                     allow_delete_own    => $shelf->allow_delete_own,
223                     allow_delete_other  => $shelf->allow_delete_other,
224                 );
225             }
226             last SWITCH;
227         }
228
229         #View a shelf
230         if ( $shelfnumber = $query->param('viewshelf') ) {
231             my $shelf = Koha::Virtualshelves->find( $shelfnumber );
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 = ( $shelf->sortfield ? $shelf->sortfield : '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 $shelf->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           => $shelf->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".$shelf->category => 1,
327                     category            => $shelf->category,
328                     itemsloop           => $items,
329                     showprivateshelves  => $shelf->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             my $shelfname = $query->param('addshelf');
342
343             if ( $shelfname ) {
344
345                 # note: a user can always add a new shelf (except database administrator account)
346                 my $shelf = eval {
347                     Koha::Virtualshelf->new(
348                         {
349                             shelfname          => $shelfname,
350                             sortfield          => $query->param('sortfield'),
351                             category           => $query->param('category'),
352                             allow_add          => $query->param('allow_add'),
353                             allow_delete_own   => $query->param('allow_delete_own'),
354                             allow_delete_other => $query->param('allow_delete_other'),
355                             owner              => $query->param('owner'),
356                         }
357                     )->store;
358                 };
359                 if ( $@ ) {
360                     $showadd = 1;
361                     push @messages, { type => 'error', code => ref($@) };
362                 } elsif ( not $shelf ) {
363                     $showadd = 1;
364                     push @messages, { type => 'error', 'error_on_insert' };
365                 } else {
366                     print $query->redirect( $pages{$type}->{redirect} . "?viewshelf=$shelfnumber" );
367                     exit;
368                 }
369
370                 $template->param(
371                     shelfname => $shelfname,
372                 );
373                 $stay = 1;
374             }
375
376         #Deleting a shelf (asking for confirmation if it has entries)
377             foreach ( $query->param() ) {
378                 /(DEL|REMSHR)-(\d+)/ or next;
379                 $delflag = 1;
380                 my $number = $2;
381                 unless ( defined $shelflist->{$number} ) {
382                     push( @paramsloop, { unrecognized => $number } );
383                     last;
384                 }
385                 #remove a share
386                 if(/REMSHR/) {
387                     my $shelf = Koha::Virtualshelves->find( $number );
388                     $shelf->delete_share( $loggedinuser );
389                     delete $shelflist->{$number} if exists $shelflist->{$number};
390                     $stay=0;
391                     next;
392                 }
393
394                 my $can_manage = ShelfPossibleAction( $loggedinuser, $number, 'manage' );
395                 my $can_delete = ShelfPossibleAction( $loggedinuser, $number, 'delete_shelf' );
396                 unless ( $can_manage or $can_delete ) {
397                     push( @paramsloop, { nopermission => $shelfnumber } );
398                     last;
399                 }
400                 my $contents;
401                 ( $contents, $totshelves ) = GetShelfContents( $number, $shelveslimit, $shelvesoffset );
402                 if ( $totshelves > 0 ) {
403                     unless ( scalar grep { /^CONFIRM-$number$/ } $query->param() ) {
404                         if ( defined $shelflist->{$number} ) {
405                             push( @paramsloop, { need_confirm => $shelflist->{$number}->{shelfname}, count => $totshelves, single => ($totshelves eq 1 ? 1:0) } );
406                             $shelflist->{$number}->{confirm} = $number;
407                         }
408                         $stay = 0;
409                         next;
410                     }
411                 }
412                 my $name;
413                 if ( defined $shelflist->{$number} ) {
414                     $name = $shelflist->{$number}->{'shelfname'};
415                     delete $shelflist->{$number};
416                 }
417                 unless( Koha::Virtualshelves->find($number)->delete ) {
418                     push( @paramsloop, { delete_fail => $name } );
419                     last;
420                 }
421                 push( @paramsloop, { delete_ok => $name } );
422
423                 $stay = 0;
424             }
425             $showadd = 1;
426             if ($stay){
427                 $template->param( shelves => 1 );
428                 $shelves = 1;
429             }
430             last SWITCH;
431         }
432     } # end of SWITCH block
433
434     (@paramsloop) and $template->param( paramsloop => \@paramsloop );
435     $showadd      and $template->param( showadd    => 1 );
436     my @shelvesloop;
437     my @shelveslooppriv;
438     my $numberCanManage = 0;
439
440     # rebuild shelflist in case a shelf has been added
441     $shelflist = GetShelves( $category, $shelveslimit, $shelvesoffset, $loggedinuser ) unless $delflag;
442     $totshelves = C4::VirtualShelves::GetShelfCount( $loggedinuser, $category ) unless $delflag;
443     foreach my $element ( sort { lc( $shelflist->{$a}->{'shelfname'} ) cmp lc( $shelflist->{$b}->{'shelfname'} ) } keys %$shelflist ) {
444         my %line;
445         $shelflist->{$element}->{shelf} = $element;
446         my $category  = $shelflist->{$element}->{'category'};
447         my $owner     = $shelflist->{$element}->{'owner'}||0;
448         my $canmanage = ShelfPossibleAction( $loggedinuser, $element, 'manage' );
449         my $candelete = ShelfPossibleAction( $loggedinuser, $element, 'delete_shelf' );
450         $shelflist->{$element}->{"viewcategory$category"} = 1;
451         $shelflist->{$element}->{manageshelf} = $canmanage;
452         $shelflist->{$element}->{allowdeletingshelf} = $candelete;
453         if($canmanage || ($loggedinuser && $owner==$loggedinuser)) {
454             $shelflist->{$element}->{'mine'} = 1;
455         }
456         my $member = GetMember( 'borrowernumber' => $owner );
457         $shelflist->{$element}->{ownername} = defined($member) ? $member->{firstname} . " " . $member->{surname} : '';
458         $numberCanManage++ if $canmanage;    # possibly outmoded
459         if ( $shelflist->{$element}->{'category'} eq '1' ) {
460             my $shelf = Koha::Virtualshelves->find( $element );
461             $shelflist->{$element}->{shares} = $shelf->is_shared;
462             push( @shelveslooppriv, $shelflist->{$element} );
463         } else {
464             push( @shelvesloop, $shelflist->{$element} );
465         }
466     }
467
468     my $url = $type eq 'opac' ? "/cgi-bin/koha/opac-shelves.pl" : "/cgi-bin/koha/virtualshelves/shelves.pl";
469     my %qhash = ();
470     foreach (qw(display viewshelf sortfield sort direction)) {
471         $qhash{$_} = $query->param($_) if $query->param($_);
472     }
473     ( scalar keys %qhash ) and $url .= '?' . join '&', map { "$_=$qhash{$_}" } keys %qhash;
474     if ( $shelflimit ) {
475         if ( $shelfnumber && $totitems ) {
476             $template->param(  pagination_bar => pagination_bar( $url, ( int( $totitems / $shelflimit ) ) + ( ( $totitems % $shelflimit ) > 0 ? 1 : 0 ), $itemoff, "itemoff" )  );
477         } elsif ( $totshelves ) {
478             $template->param(
479                  pagination_bar => pagination_bar( $url, ( int( $totshelves / $shelveslimit ) ) + ( ( $totshelves % $shelveslimit ) > 0 ? 1 : 0 ), $shelfoff, "shelfoff" )  );
480         }
481     }
482
483     $template->param(
484         shelveslooppriv                                                    => \@shelveslooppriv,
485         shelvesloop                                                        => \@shelvesloop,
486         shelvesloopall                                                     => [ ( @shelvesloop, @shelveslooppriv ) ],
487         numberCanManage                                                    => $numberCanManage,
488         "BiblioDefaultView" . C4::Context->preference("BiblioDefaultView") => 1,
489         csv_profiles                                                       => GetCsvProfilesLoop('marc')
490     );
491
492 #Next call updates the shelves for the Lists button.
493 #May not always be needed (when nothing changed), but doesn't take much.
494     my ($total, $pubshelves, $barshelves) = C4::VirtualShelves::GetSomeShelfNames($loggedinuser, 'MASTHEAD');
495     $template->param(
496             barshelves     => $total->{bartotal},
497             barshelvesloop => $barshelves,
498             pubshelves     => $total->{pubtotal},
499             pubshelvesloop => $pubshelves,
500             messages       => \@messages,
501     );
502
503     output_html_with_http_headers $query, $cookie, $template->output;
504 }
505
506 1;
507 __END__
508
509 =head1 NAME
510
511 VirtualShelves/Page.pm
512
513 =head1 DESCRIPTION
514
515 Module used for both OPAC and intranet pages.
516
517 =head1 CGI PARAMETERS
518
519 =over 4
520
521 =item C<modifyshelfcontents>
522
523 If this script has to modify the shelf content.
524
525 =item C<shelfnumber>
526
527 To know on which shelf to work.
528
529 =item C<addbarcode>
530
531 =item C<op>
532
533  Op can be:
534     * modif: show the template allowing modification of the shelves;
535     * modifsave: save changes from modif mode.
536
537 =item C<viewshelf>
538
539 Load template with 'viewshelves param' displaying the shelf's information.
540
541 =item C<shelves>
542
543 If the param shelves == 1, then add or delete a shelf.
544
545 =item C<addshelf>
546
547 If the param shelves == 1, then addshelf is the name of the shelf to add.
548
549 =back
550
551 =cut