Bug 5549 : Let Timestamp do the right thing if passed a DateTime
[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 under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 2 of the License, or (at your option) any later
11 # version.
12 #
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License along
18 # with Koha; if not, write to the Free Software Foundation, Inc.,
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20
21 # perldoc at the end of the file, per convention.
22
23 use strict;
24 use warnings;
25 use CGI;
26 use C4::VirtualShelves qw/:DEFAULT RefreshShelvesSummary/;
27 use C4::Biblio;
28 use C4::Items;
29 use C4::Koha;
30 use C4::Auth qw/get_session/;
31 use C4::Members;
32 use C4::Output;
33 use C4::Dates qw/format_date/;
34 use C4::Tags qw(get_tags);
35 use Exporter;
36 use Data::Dumper;
37 use C4::Csv;
38 use C4::XSLT;
39
40 use vars qw($debug @EXPORT @ISA $VERSION);
41
42 BEGIN {
43     $VERSION = 1.01;
44     @ISA     = qw(Exporter);
45     @EXPORT  = qw(&shelfpage);
46     $debug   = $ENV{DEBUG} || 0;
47 }
48
49 our %pages = (
50     intranet => { redirect => '/cgi-bin/koha/virtualshelves/shelves.pl', },
51     opac     => { redirect => '/cgi-bin/koha/opac-shelves.pl', },
52 );
53
54 sub shelfpage ($$$$$) {
55     my ( $type, $query, $template, $loggedinuser, $cookie ) = @_;
56     ( $pages{$type} ) or $type = 'opac';
57     $query            or die "No query";
58     $template         or die "No template";
59     $template->param(  loggedinuser => $loggedinuser  );
60     my $edit;
61     my $shelves;
62     my @paramsloop;
63     my $totitems;
64     my $shelfoff    = ( $query->param('shelfoff') ? $query->param('shelfoff') : 1 );
65     $template->{VARS}->{'shelfoff'} = $shelfoff;
66     my $itemoff     = ( $query->param('itemoff')  ? $query->param('itemoff')  : 1 );
67     my $displaymode = ( $query->param('display')  ? $query->param('display')  : 'publicshelves' );
68     my ( $shelflimit, $shelfoffset, $shelveslimit, $shelvesoffset );
69     my $marcflavour = C4::Context->preference("marcflavour");
70
71     # get biblionumbers stored in the cart
72     my @cart_list;
73     my $cart_cookie = ( $type eq 'opac' ? "bib_list" : "intranet_bib_list" );
74     if($query->cookie($cart_cookie)){
75         my $cart_list = $query->cookie($cart_cookie);
76         @cart_list = split(/\//, $cart_list);
77     }
78
79     $shelflimit = ( $type eq 'opac' ? C4::Context->preference('OPACnumSearchResults') : C4::Context->preference('numSearchResults') );
80     $shelflimit = $shelflimit || 20;
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, $totshelves ) = GetShelves( $category, $shelveslimit, $shelvesoffset, $loggedinuser );
87
88     #Get a list of private shelves for possible deletion. Only do this when we've defaulted to public shelves
89     my ( $privshelflist, $privtotshelves );
90     if ( $category == 2 ) {
91         ( $privshelflist, $privtotshelves ) = GetShelves( 1, $shelveslimit, $shelvesoffset, $loggedinuser );
92     }
93     my $op = $query->param('op');
94
95     #    my $imgdir = getitemtypeimagesrc();
96     #    my $itemtypes = GetItemTypes();
97
98     # the format of this is unindented for ease of diff comparison to the old script
99     # Note: do not mistake the assignment statements below for comparisons!
100     if ( $query->param('modifyshelfcontents') ) {
101         my ( $shelfnumber, $barcode, $item, $biblio );
102         if ( $shelfnumber = $query->param('viewshelf') ) {
103             if ( ShelfPossibleAction( $loggedinuser, $shelfnumber, 'manage' ) ) {
104                 if ( $barcode = $query->param('addbarcode') ) {
105                     $item = GetItem( 0, $barcode );
106                     if (defined $item && $item->{'itemnumber'}){
107                         $biblio = GetBiblioFromItemNumber( $item->{'itemnumber'} );
108                         AddToShelf( $biblio->{'biblionumber'}, $shelfnumber )
109                           or push @paramsloop, { duplicatebiblio => $barcode };
110                     } else {
111                         push @paramsloop, { failgetitem => $barcode };
112                     }
113                 } else {
114                     ( grep { /REM-(\d+)/ } $query->param ) or push @paramsloop, { nobarcode => 1 };
115                     foreach ( $query->param ) {
116                         /REM-(\d+)/ or next;
117                         $debug and warn "SHELVES: user $loggedinuser removing item $1 from shelf $shelfnumber";
118                         DelFromShelf( $1, $shelfnumber );    # $1 is biblionumber
119                     }
120                 }
121             } else {
122                 push @paramsloop, { nopermission => $shelfnumber };
123             }
124         } else {
125             push @paramsloop, { noshelfnumber => 1 };
126         }
127     }
128
129     my $showadd = 1;
130
131     # set the default tab, etc. (for OPAC)
132     my $shelf_type = ( $query->param('display') ? $query->param('display') : 'publicshelves' );
133     if ( defined $shelf_type ) {
134         if ( $shelf_type eq 'privateshelves' ) {
135             $template->param( showprivateshelves => 1 );
136         } elsif ( $shelf_type eq 'publicshelves' ) {
137             $template->param( showpublicshelves => 1 );
138             $showadd = 0;
139         } else {
140             $debug and warn "Invalid 'display' param ($shelf_type)";
141         }
142     } elsif ( $loggedinuser == -1 ) {
143         $template->param( showpublicshelves => 1 );
144     } else {
145         $template->param( showprivateshelves => 1 );
146     }
147
148     my ( $okmanage, $okview );
149     my $shelfnumber = $query->param('shelfnumber') || $query->param('viewshelf');
150     if ($shelfnumber) {
151         $okmanage = ShelfPossibleAction( $loggedinuser, $shelfnumber, 'manage' );
152         $okview   = ShelfPossibleAction( $loggedinuser, $shelfnumber, 'view' );
153     }
154
155     my $delflag = 0;
156
157   SWITCH: {
158         if ($op) {
159             unless ($okmanage) {
160                 push @paramsloop, { nopermission => $shelfnumber };
161                 last SWITCH;
162             }
163             if ( $op eq 'modifsave' ) {
164                 my $shelf = {
165                     'shelfname' => $query->param('shelfname'),
166                     'category'  => $query->param('category'),
167                     'sortfield' => $query->param('sortfield'),
168                 };
169
170                 ModShelf( $shelfnumber, $shelf );
171                 if($displaymode eq "viewshelf"){
172                     print $query->redirect( $pages{$type}->{redirect} . "?viewshelf=$shelfnumber" );
173                 } elsif($displaymode eq "publicshelves"){
174                     print $query->redirect( $pages{$type}->{redirect} );
175                 } else {
176                     print $query->redirect( $pages{$type}->{redirect} . "?display=privateshelves" );
177                 }
178                 exit;
179
180             } elsif ( $op eq 'modif' ) {
181                 my ( $shelfnumber2, $shelfname, $owner, $category, $sortfield ) = GetShelf($shelfnumber);
182                 my $member = GetMember( 'borrowernumber' => $owner );
183                 my $ownername = defined($member) ? $member->{firstname} . " " . $member->{surname} : '';
184                 $edit = 1;
185                 $template->param(
186                     edit                => 1,
187                     display             => $displaymode,
188                     shelfnumber         => $shelfnumber2,
189                     shelfname           => $shelfname,
190                     owner               => $owner,
191                     ownername           => $ownername,
192                     "category$category" => 1,
193                     category            => $category,
194                     "sort_$sortfield"   => 1,
195                 );
196             }
197             last SWITCH;
198         }
199         if ( $shelfnumber = $query->param('viewshelf') ) {
200             # explicitly fetch this shelf
201             my ($shelfnumber2,$shelfname,$owner,$category,$sorton) = GetShelf($shelfnumber);
202
203             $template->param( 'AllowOnShelfHolds' => C4::Context->preference('AllowOnShelfHolds') );
204             if (C4::Context->preference('TagsEnabled')) {
205                 $template->param(TagsEnabled => 1);
206                     foreach (qw(TagsShowOnList TagsInputOnList)) {
207                     C4::Context->preference($_) and $template->param($_ => 1);
208                 }
209             }
210             #check that the user can view the shelf
211             if ( ShelfPossibleAction( $loggedinuser, $shelfnumber, 'view' ) ) {
212                 my $items;
213                 my $authorsort;
214                 my $yearsort;
215                 my $tag_quantity;
216                 my $sortfield = ( $query->param('sortfield') ? $query->param('sortfield') : 'title' );
217                 if ( $sortfield eq 'author' ) {
218                     $authorsort = 'author';
219                 }
220                 if ( $sortfield eq 'year' ) {
221                     $yearsort = 'year';
222                 }
223                 ( $items, $totitems ) = GetShelfContents( $shelfnumber, $shelflimit, $shelfoffset );
224                 for my $this_item (@$items) {
225                     my $biblionumber = $this_item->{'biblionumber'};
226                     my $record = GetMarcBiblio($biblionumber);
227                     $this_item->{XSLTBloc} =
228                         XSLTParse4Display($biblionumber, $record, 'Results', 'opac')
229                             if C4::Context->preference("OPACXSLTResultsDisplay") && $type eq 'opac';
230
231                     # the virtualshelfcontents table does not store these columns nor are they retrieved from the items
232                     # and itemtypes tables, so I'm commenting them out for now to quiet the log -crn
233                     #$this_item->{imageurl} = $imgdir."/".$itemtypes->{ $this_item->{itemtype}  }->{'imageurl'};
234                     #$this_item->{'description'} = $itemtypes->{ $this_item->{itemtype} }->{'description'};
235                     $this_item->{'dateadded'} = format_date( $this_item->{'dateadded'} );
236                     $this_item->{'imageurl'}  = getitemtypeinfo( $this_item->{'itemtype'} )->{'imageurl'};
237                     $this_item->{'coins'}     = GetCOinSBiblio( $record );
238                     $this_item->{'subtitle'} = GetRecordValue('subtitle', $record, GetFrameworkCode($this_item->{'biblionumber'}));
239                     $this_item->{'normalized_upc'}  = GetNormalizedUPC(       $record,$marcflavour);
240                     $this_item->{'normalized_ean'}  = GetNormalizedEAN(       $record,$marcflavour);
241                     $this_item->{'normalized_oclc'} = GetNormalizedOCLCNumber($record,$marcflavour);
242                     $this_item->{'normalized_isbn'} = GetNormalizedISBN(undef,$record,$marcflavour);
243                     # Getting items infos for location display
244                     my @items_infos = &GetItemsLocationInfo( $this_item->{'biblionumber'});
245                     $this_item->{'itemsissued'} = CountItemsIssued( $this_item->{'biblionumber'} );
246                     $this_item->{'ITEM_RESULTS'} = \@items_infos;
247                     if ( grep {$_ eq $biblionumber} @cart_list) {
248                         $this_item->{'incart'} = 1;
249                     }
250
251                     if (C4::Context->preference('TagsEnabled') and $tag_quantity = C4::Context->preference('TagsShowOnList')) {
252                         $this_item->{'TagLoop'} = get_tags({
253                             biblionumber=>$this_item->{'biblionumber'}, approved=>1, 'sort'=>'-weight',
254                             limit=>$tag_quantity
255                             });
256                     }
257
258                 }
259                 push @paramsloop, { display => 'privateshelves' } if $category == 1;
260                 $showadd = 1;
261                 my $i = 0;
262                 my $manageshelf = ShelfPossibleAction( $loggedinuser, $shelfnumber, 'manage' );
263                 $template->param(
264                     shelfname           => $shelfname,
265                     shelfnumber         => $shelfnumber,
266                     viewshelf           => $shelfnumber,
267                     authorsort          => $authorsort,
268                     yearsort            => $yearsort,
269                     manageshelf         => $manageshelf,
270                     "category$category" => 1,
271                     category            => $category,
272                     itemsloop           => $items,
273                 );
274             } else {
275                 push @paramsloop, { nopermission => $shelfnumber };
276             }
277             last SWITCH;
278         }
279         if ( $query->param('shelves') ) {
280             my $stay = 1;
281             if ( my $newshelf = $query->param('addshelf') ) {
282
283                 # note: a user can always add a new shelf
284                 my $shelfnumber = AddShelf( $newshelf, $query->param('owner'), $query->param('category'), $query->param('sortfield') );
285                 $stay = 1;
286                 if ( $shelfnumber == -1 ) {    #shelf already exists.
287                     $showadd = 1;
288                     push @paramsloop, { already => $newshelf };
289                     $template->param( shelfnumber => $shelfnumber );
290                 } else {
291                     print $query->redirect( $pages{$type}->{redirect} . "?viewshelf=$shelfnumber" );
292                     exit;
293                 }
294             }
295             foreach ( $query->param() ) {
296                 /DEL-(\d+)/ or next;
297                 $delflag = 1;
298                 my $number = $1;
299                 unless ( defined $shelflist->{$number} || defined $privshelflist->{$number} ) {
300                     push( @paramsloop, { unrecognized => $number } );
301                     last;
302                 }
303                 unless ( ShelfPossibleAction( $loggedinuser, $number, 'manage' ) ) {
304                     push( @paramsloop, { nopermission => $shelfnumber } );
305                     last;
306                 }
307                 my $contents;
308                 ( $contents, $totshelves ) = GetShelfContents( $number, $shelveslimit, $shelvesoffset );
309                 if ( my $count = scalar @$contents ) {
310                     unless ( scalar grep { /^CONFIRM-$number$/ } $query->param() ) {
311                         if ( defined $shelflist->{$number} ) {
312                             push( @paramsloop, { need_confirm => $shelflist->{$number}->{shelfname}, count => $count, single => ($count eq 1 ? 1:0) } );
313                             $shelflist->{$number}->{confirm} = $number;
314                         } else {
315                             push( @paramsloop, { need_confirm => $privshelflist->{$number}->{shelfname}, count => $count } );
316                             $privshelflist->{$number}->{confirm} = $number;
317                         }
318                         $stay = 0;
319                         next;
320                     }
321                 }
322                 my $name;
323                 if ( defined $shelflist->{$number} ) {
324                     $name = $shelflist->{$number}->{'shelfname'};
325                     delete $shelflist->{$number};
326                 } else {
327                     $name = $privshelflist->{$number}->{'shelfname'};
328                     delete $privshelflist->{$number};
329                 }
330                 unless ( DelShelf($number) ) {
331                     push( @paramsloop, { delete_fail => $name } );
332                     last;
333                 }
334                 push( @paramsloop, { delete_ok => $name } );
335
336                 # print $query->redirect($pages{$type}->{redirect}); exit;
337                 $stay = 0;
338             }
339             $showadd = 1;
340             if ($stay){
341                 $template->param( shelves => 1 );
342                 $shelves = 1;
343             }
344             last SWITCH;
345         }
346     }
347
348     (@paramsloop) and $template->param( paramsloop => \@paramsloop );
349     $showadd      and $template->param( showadd    => 1 );
350     my @shelvesloop;
351     my @shelveslooppriv;
352     my $numberCanManage = 0;
353
354     # rebuild shelflist in case a shelf has been added
355     ( $shelflist, $totshelves ) = GetShelves( $category, $shelveslimit, $shelvesoffset, $loggedinuser ) unless $delflag;
356     foreach my $element ( sort { lc( $shelflist->{$a}->{'shelfname'} ) cmp lc( $shelflist->{$b}->{'shelfname'} ) } keys %$shelflist ) {
357         my %line;
358         $shelflist->{$element}->{shelf} = $element;
359         my $category  = $shelflist->{$element}->{'category'};
360         my $owner     = $shelflist->{$element}->{'owner'};
361         my $canmanage = ShelfPossibleAction( $loggedinuser, $element, 'manage' );
362         my $sortfield = $shelflist->{$element}->{'sortfield'};
363         if ( $sortfield ){
364             if ( $sortfield eq 'author' ) {
365                 $shelflist->{$element}->{"authorsort"} = 'author';
366             } elsif ( $sortfield eq 'year' ) {
367                 $shelflist->{$element}->{"yearsort"} = 'year';
368             }
369         }
370         $shelflist->{$element}->{"viewcategory$category"} = 1;
371         $shelflist->{$element}->{manageshelf} = $canmanage;
372         if ( $owner eq $loggedinuser or $canmanage ) {
373             $shelflist->{$element}->{'mine'} = 1;
374         }
375         my $member = GetMember( 'borrowernumber' => $owner );
376         $shelflist->{$element}->{ownername} = defined($member) ? $member->{firstname} . " " . $member->{surname} : '';
377         $numberCanManage++ if $canmanage;    # possibly outmoded
378         if ( $shelflist->{$element}->{'category'} eq '1' ) {
379             push( @shelveslooppriv, $shelflist->{$element} );
380         } else {
381             push( @shelvesloop, $shelflist->{$element} );
382         }
383     }
384
385     my $url = $type eq 'opac' ? "/cgi-bin/koha/opac-shelves.pl" : "/cgi-bin/koha/virtualshelves/shelves.pl";
386     my %qhash = ();
387     foreach (qw(display viewshelf sortfield)) {
388         $qhash{$_} = $query->param($_) if $query->param($_);
389     }
390     ( scalar keys %qhash ) and $url .= '?' . join '&', map { "$_=$qhash{$_}" } keys %qhash;
391     if ( $shelfnumber && $totitems ) {
392         $template->param(  pagination_bar => pagination_bar( $url, ( int( $totitems / $shelflimit ) ) + ( ( $totitems % $shelflimit ) > 0 ? 1 : 0 ), $itemoff, "itemoff" )  );
393     } elsif ( $totshelves ) {
394         $template->param(
395              pagination_bar => pagination_bar( $url, ( int( $totshelves / $shelveslimit ) ) + ( ( $totshelves % $shelveslimit ) > 0 ? 1 : 0 ), $shelfoff, "shelfoff" )  );
396     }
397     $template->param(
398         shelveslooppriv                                                    => \@shelveslooppriv,
399         shelvesloop                                                        => \@shelvesloop,
400         shelvesloopall                                                     => [ ( @shelvesloop, @shelveslooppriv ) ],
401         numberCanManage                                                    => $numberCanManage,
402         "BiblioDefaultView" . C4::Context->preference("BiblioDefaultView") => 1,
403         csv_profiles                                                       => GetCsvProfilesLoop()
404     );
405     if (   $shelfnumber
406         or $shelves
407         or $edit ) {
408         $template->param( vseflag => 1 );
409     }
410     if ($shelves or    # note: this part looks duplicative, but is intentional
411         $edit
412       ) {
413         $template->param( seflag => 1 );
414     }
415
416     #FIXME: This refresh really only needs to happen when there is a modification of some sort
417     #       to the shelves, but the above code is so convoluted in its handling of the various
418     #       options, it is easier to do this refresh every time C4::VirtualShelves::Page.pm is
419     #       called
420
421     my ( $total, $pubshelves, $barshelves ) = RefreshShelvesSummary( $query->cookie("CGISESSID"), $loggedinuser, ( $loggedinuser == -1 ? 20 : 10 ) );
422
423     if ( defined $barshelves ) {
424         $template->param(
425             barshelves     => scalar( @{ $barshelves } ),
426             barshelvesloop => $barshelves,
427         );
428         $template->param( bartotal => $total->{'bartotal'}, ) if ( $total->{'bartotal'} > scalar( @{ $barshelves } ) );
429     }
430
431     if ( defined $pubshelves ) {
432         $template->param(
433             pubshelves     => scalar( @{ $pubshelves } ),
434             pubshelvesloop => $pubshelves,
435         );
436         $template->param( pubtotal => $total->{'pubtotal'}, ) if ( $total->{'pubtotal'} > scalar( @{ $pubshelves } ) );
437     }
438
439     output_html_with_http_headers $query, $cookie, $template->output;
440 }
441
442 1;
443 __END__
444
445 =head1 NAME
446
447 VirtualShelves/Page.pm
448
449 =head1 DESCRIPTION
450
451 Module used for both OPAC and intranet pages.
452
453 =head1 CGI PARAMETERS
454
455 =over 4
456
457 =item C<modifyshelfcontents>
458
459 If this script has to modify the shelf content.
460
461 =item C<shelfnumber>
462
463 To know on which shelf to work.
464
465 =item C<addbarcode>
466
467 =item C<op>
468
469  Op can be:
470     * modif: show the template allowing modification of the shelves;
471     * modifsave: save changes from modif mode.
472
473 =item C<viewshelf>
474
475 Load template with 'viewshelves param' displaying the shelf's information.
476
477 =item C<shelves>
478
479 If the param shelves == 1, then add or delete a shelf.
480
481 =item C<addshelf>
482
483 If the param shelves == 1, then addshelf is the name of the shelf to add.
484
485 =back
486
487 =cut