Bug 12995 - script update_totalissues.pl stops on corrupted record
[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
26 use CGI;
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::Koha;
34 use C4::Auth qw/get_session/;
35 use C4::Members;
36 use C4::Output;
37 use C4::Dates qw/format_date/;
38 use C4::Tags qw(get_tags);
39 use C4::Csv;
40 use C4::XSLT;
41
42 use constant VIRTUALSHELVES_COUNT => 20;
43
44 use vars qw($debug @EXPORT @ISA $VERSION);
45
46 BEGIN {
47     $VERSION = 3.07.00.049;
48     @ISA     = qw(Exporter);
49     @EXPORT  = qw(&shelfpage);
50     $debug   = $ENV{DEBUG} || 0;
51 }
52
53 our %pages = (
54     intranet => { redirect => '/cgi-bin/koha/virtualshelves/shelves.pl', },
55     opac     => { redirect => '/cgi-bin/koha/opac-shelves.pl', },
56 );
57
58 sub shelfpage {
59     my ( $type, $query, $template, $loggedinuser, $cookie ) = @_;
60     ( $pages{$type} ) or $type = 'opac';
61     $query            or die "No query";
62     $template         or die "No template";
63     $template->param(
64     loggedinuser => $loggedinuser,
65     OpacAllowPublicListCreation => C4::Context->preference('OpacAllowPublicListCreation'),
66     );
67     my $edit;
68     my $shelves;
69     my @paramsloop;
70     my $totitems;
71     my $shelfoff    = ( $query->param('shelfoff') ? $query->param('shelfoff') : 1 );
72     $template->{VARS}->{'shelfoff'} = $shelfoff;
73     my $itemoff     = ( $query->param('itemoff')  ? $query->param('itemoff')  : 1 );
74     my $displaymode = ( $query->param('display')  ? $query->param('display')  : 'publicshelves' );
75     my ( $shelflimit, $shelfoffset, $shelveslimit, $shelvesoffset );
76     my $marcflavour = C4::Context->preference("marcflavour");
77
78     # get biblionumbers stored in the cart
79     my @cart_list;
80     my $cart_cookie = ( $type eq 'opac' ? "bib_list" : "intranet_bib_list" );
81     if($query->cookie($cart_cookie)){
82         my $cart_list = $query->cookie($cart_cookie);
83         @cart_list = split(/\//, $cart_list);
84     }
85
86     $shelflimit = ( $type eq 'opac' ? C4::Context->preference('OPACnumSearchResults') : C4::Context->preference('numSearchResults') );
87     $shelflimit = $shelflimit || ShelvesMax('MGRPAGE');
88     $shelfoffset   = ( $itemoff - 1 ) * $shelflimit;     # Sets the offset to begin retrieving items at
89     $shelveslimit  = $shelflimit;                        # Limits number of shelves returned for a given query (row_count)
90     $shelvesoffset = ( $shelfoff - 1 ) * $shelflimit;    # Sets the offset to begin retrieving shelves at (offset)
91                                                 # getting the Shelves list
92     my $category = ( ( $displaymode eq 'privateshelves' ) ? 1 : 2 );
93     my ( $shelflist, $totshelves ) = GetShelves( $category, $shelveslimit, $shelvesoffset, $loggedinuser );
94
95     #Get a list of private shelves for possible deletion. Only do this when we've defaulted to public shelves
96     my ( $privshelflist, $privtotshelves );
97     if ( $category == 2 ) {
98         ( $privshelflist, $privtotshelves ) = GetShelves( 1, $shelveslimit, $shelvesoffset, $loggedinuser );
99     }
100     my $op = $query->param('op');
101
102     # the format of this is unindented for ease of diff comparison to the old script
103     # Note: do not mistake the assignment statements below for comparisons!
104     if ( $query->param('modifyshelfcontents') ) {
105         my ( $shelfnumber, $barcode, $item, $biblio );
106         if ( $shelfnumber = $query->param('viewshelf') ) {
107             #add to shelf
108             if($barcode = $query->param('addbarcode') ) {
109                 if(ShelfPossibleAction( $loggedinuser, $shelfnumber, 'add')) {
110                     $item = GetItem( 0, $barcode);
111                     if (defined $item && $item->{'itemnumber'}) {
112                         $biblio = GetBiblioFromItemNumber( $item->{'itemnumber'} );
113                         AddToShelf( $biblio->{'biblionumber'}, $shelfnumber, $loggedinuser)
114                           or push @paramsloop, { duplicatebiblio => $barcode };
115                     }
116                     else {
117                         push @paramsloop, { failgetitem => $barcode };
118                     }
119                 }
120                 else {
121                     push @paramsloop, { nopermission => $shelfnumber };
122                 }
123             }
124             elsif(grep { /REM-(\d+)/ } $query->param) {
125             #remove item(s) from shelf
126                 if(ShelfPossibleAction($loggedinuser, $shelfnumber, 'delete')) {
127                 #This is just a general okay; DelFromShelf checks further
128                     my @bib;
129                     foreach($query->param) {
130                         /REM-(\d+)/ or next;
131                         push @bib, $1; #$1 is biblionumber
132                     }
133                     my $t= DelFromShelf(\@bib, $shelfnumber, $loggedinuser);
134                     if($t==0) {
135                         push @paramsloop, {nothingdeleted => $shelfnumber};
136                     }
137                     elsif($t<@bib) {
138                         push @paramsloop, {somedeleted => $shelfnumber};
139                     }
140                 }
141                 else {
142                     push @paramsloop, { nopermission => $shelfnumber };
143                 }
144             }
145         }
146         else {
147             push @paramsloop, { noshelfnumber => 1 };
148         }
149     }
150
151     my $showadd = 1;
152
153     # set the default tab, etc. (for OPAC)
154     my $shelf_type = ( $query->param('display') ? $query->param('display') : 'publicshelves' );
155     if ( defined $shelf_type ) {
156         if ( $shelf_type eq 'privateshelves' ) {
157             $template->param( showprivateshelves => 1 );
158         } elsif ( $shelf_type eq 'publicshelves' ) {
159             $template->param( showpublicshelves => 1 );
160             $showadd = 0;
161         } else {
162             $debug and warn "Invalid 'display' param ($shelf_type)";
163         }
164     } elsif ( $loggedinuser == -1 ) {
165         $template->param( showpublicshelves => 1 );
166     } else {
167         $template->param( showprivateshelves => 1 );
168     }
169
170     my ( $okmanage, $okview );
171     my $shelfnumber = $query->param('shelfnumber') || $query->param('viewshelf');
172     if ($shelfnumber) {
173         $okmanage = ShelfPossibleAction( $loggedinuser, $shelfnumber, 'manage' );
174         $okview   = ShelfPossibleAction( $loggedinuser, $shelfnumber, 'view' );
175     }
176
177     my $delflag = 0;
178
179   SWITCH: {
180         if ($op) {
181         #Saving modified shelf
182             if ( $op eq 'modifsave' ) {
183                 unless ($okmanage) {
184                         push @paramsloop, { nopermission => $shelfnumber };
185                         last SWITCH;
186                 }
187                 my $shelf = {
188                     shelfname          => $query->param('shelfname'),
189                     sortfield          => $query->param('sortfield'),
190                     allow_add          => $query->param('allow_add'),
191                     allow_delete_own   => $query->param('allow_delete_own'),
192                     allow_delete_other => $query->param('allow_delete_other'),
193                 };
194                 if($query->param('category')) { #optional
195                     $shelf->{category}= $query->param('category');
196                 }
197                 unless(ModShelf($shelfnumber, $shelf )) {
198                   push @paramsloop, {modifyfailure => $shelf->{shelfname}};
199                   last SWITCH;
200                 }
201
202                 if($displaymode eq "viewshelf"){
203                     print $query->redirect( $pages{$type}->{redirect} . "?viewshelf=$shelfnumber" );
204                 } elsif($displaymode eq "publicshelves"){
205                     print $query->redirect( $pages{$type}->{redirect} );
206                 } else {
207                     print $query->redirect( $pages{$type}->{redirect} . "?display=privateshelves" );
208                 }
209                 exit;
210             }
211         #Editing a shelf
212         elsif ( $op eq 'modif' ) {
213                 my ( $shelfnumber2, $shelfname, $owner, $category, $sortfield, $allow_add, $allow_delete_own, $allow_delete_other) = GetShelf($shelfnumber);
214                 my $member = GetMember( 'borrowernumber' => $owner );
215                 my $ownername = defined($member) ? $member->{firstname} . " " . $member->{surname} : '';
216                 $edit = 1;
217                 $template->param(
218                     edit                => 1,
219                     display             => $displaymode,
220                     shelfnumber         => $shelfnumber2,
221                     shelfname           => $shelfname,
222                     owner               => $owner,
223                     ownername           => $ownername,
224                     "category$category" => 1,
225                     category            => $category,
226                     sortfield           => $sortfield,
227                     allow_add           => $allow_add,
228                     allow_delete_own    => $allow_delete_own,
229                     allow_delete_other  => $allow_delete_other,
230                 );
231             }
232             last SWITCH;
233         }
234
235         #View a shelf
236         if ( $shelfnumber = $query->param('viewshelf') ) {
237             # explicitly fetch this shelf
238             my ($shelfnumber2,$shelfname,$owner,$category,$sorton) = GetShelf($shelfnumber);
239
240             $template->param(
241                 'AllowOnShelfHolds'     => C4::Context->preference('AllowOnShelfHolds'),
242                 'DisplayMultiPlaceHold' => C4::Context->preference('DisplayMultiPlaceHold'),
243             );
244             if (C4::Context->preference('TagsEnabled')) {
245                 $template->param(TagsEnabled => 1);
246                     foreach (qw(TagsShowOnList TagsInputOnList)) {
247                     C4::Context->preference($_) and $template->param($_ => 1);
248                 }
249             }
250             #check that the user can view the shelf
251             if ( ShelfPossibleAction( $loggedinuser, $shelfnumber, 'view' ) ) {
252                 my $items;
253                 my $tag_quantity;
254                 my $sortfield = ( $sorton ? $sorton : 'title' );
255                 $sortfield = $query->param('sort') || $sortfield; ## Passed in sorting overrides default sorting
256                 my $direction = $query->param('direction') || 'asc';
257                 $template->param(
258                     sort      => $sortfield,
259                     direction => $direction,
260                 );
261                 ( $items, $totitems ) = GetShelfContents( $shelfnumber, $shelflimit, $shelfoffset, $sortfield, $direction );
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                 }
300                 if($type eq 'intranet'){
301                     # Build drop-down list for 'Add To:' menu...
302                     my ($totalref, $pubshelves, $barshelves)=
303                     C4::VirtualShelves::GetSomeShelfNames($loggedinuser,'COMBO',1);
304                     $template->param(
305                         addbarshelves     => $totalref->{bartotal},
306                         addbarshelvesloop => $barshelves,
307                         addpubshelves     => $totalref->{pubtotal},
308                         addpubshelvesloop => $pubshelves,
309                     );
310                 }
311                 push @paramsloop, { display => 'privateshelves' } if $category == 1;
312                 $showadd = 1;
313                 my $i = 0;
314                 my $manageshelf = ShelfPossibleAction( $loggedinuser, $shelfnumber, 'manage' );
315                 $template->param(
316                     shelfname           => $shelfname,
317                     shelfnumber         => $shelfnumber,
318                     viewshelf           => $shelfnumber,
319                     sortfield           => $sortfield,
320                     manageshelf         => $manageshelf,
321                     allowremovingitems  => ShelfPossibleAction( $loggedinuser, $shelfnumber, 'delete'),
322                     allowaddingitem     => ShelfPossibleAction( $loggedinuser, $shelfnumber, 'add'),
323                     "category$category" => 1,
324                     category            => $category,
325                     itemsloop           => $items,
326                     showprivateshelves  => $category==1,
327                 );
328             } else {
329                 push @paramsloop, { nopermission => $shelfnumber };
330             }
331             last SWITCH;
332         }
333
334         if ( $query->param('shelves') ) {
335             my $stay = 1;
336
337         #Add a shelf
338             if ( my $newshelf = $query->param('addshelf') ) {
339
340                 # note: a user can always add a new shelf (except database administrator account)
341                 my $shelfnumber = AddShelf( {
342                     shelfname => $newshelf,
343                     sortfield => $query->param('sortfield'),
344                     category => $query->param('category'),
345                     allow_add => $query->param('allow_add'),
346                     allow_delete_own => $query->param('allow_delete_own'),
347                     allow_delete_other => $query->param('allow_delete_other'),
348                     },
349                     $query->param('owner') );
350                 $stay = 1;
351                 if( !$shelfnumber ) {
352                     push @paramsloop, { addshelf_failed => 1 };
353                 } elsif ( $shelfnumber == -1 ) {    #shelf already exists.
354                     $showadd = 1;
355                     push @paramsloop, { already => $newshelf };
356                     $template->param( shelfnumber => $shelfnumber );
357                 } else {
358                     print $query->redirect( $pages{$type}->{redirect} . "?viewshelf=$shelfnumber" );
359                     exit;
360                 }
361             }
362
363         #Deleting a shelf (asking for confirmation if it has entries)
364             foreach ( $query->param() ) {
365                 /(DEL|REMSHR)-(\d+)/ or next;
366                 $delflag = 1;
367                 my $number = $2;
368                 unless ( defined $shelflist->{$number} || defined $privshelflist->{$number} ) {
369                     push( @paramsloop, { unrecognized => $number } );
370                     last;
371                 }
372                 #remove a share
373                 if(/REMSHR/) {
374                     RemoveShare($loggedinuser, $number);
375                     delete $shelflist->{$number} if exists $shelflist->{$number};
376                     delete $privshelflist->{$number} if exists $privshelflist->{$number};
377                     $stay=0;
378                     next;
379                 }
380                 #
381                 unless ( ShelfPossibleAction( $loggedinuser, $number, 'manage' ) ) {
382                     push( @paramsloop, { nopermission => $shelfnumber } );
383                     last;
384                 }
385                 my $contents;
386                 ( $contents, $totshelves ) = GetShelfContents( $number, $shelveslimit, $shelvesoffset );
387                 if ( $totshelves > 0 ) {
388                     unless ( scalar grep { /^CONFIRM-$number$/ } $query->param() ) {
389                         if ( defined $shelflist->{$number} ) {
390                             push( @paramsloop, { need_confirm => $shelflist->{$number}->{shelfname}, count => $totshelves, single => ($totshelves eq 1 ? 1:0) } );
391                             $shelflist->{$number}->{confirm} = $number;
392                         } else {
393                             push( @paramsloop, { need_confirm => $privshelflist->{$number}->{shelfname}, count => $totshelves } );
394                             $privshelflist->{$number}->{confirm} = $number;
395                         }
396                         $stay = 0;
397                         next;
398                     }
399                 }
400                 my $name;
401                 if ( defined $shelflist->{$number} ) {
402                     $name = $shelflist->{$number}->{'shelfname'};
403                     delete $shelflist->{$number};
404                 } else {
405                     $name = $privshelflist->{$number}->{'shelfname'};
406                     delete $privshelflist->{$number};
407                 }
408                 unless ( DelShelf($number) ) {
409                     push( @paramsloop, { delete_fail => $name } );
410                     last;
411                 }
412                 push( @paramsloop, { delete_ok => $name } );
413
414                 $stay = 0;
415             }
416             $showadd = 1;
417             if ($stay){
418                 $template->param( shelves => 1 );
419                 $shelves = 1;
420             }
421             last SWITCH;
422         }
423     } # end of SWITCH block
424
425     (@paramsloop) and $template->param( paramsloop => \@paramsloop );
426     $showadd      and $template->param( showadd    => 1 );
427     my @shelvesloop;
428     my @shelveslooppriv;
429     my $numberCanManage = 0;
430
431     # rebuild shelflist in case a shelf has been added
432     ( $shelflist, $totshelves ) = GetShelves( $category, $shelveslimit, $shelvesoffset, $loggedinuser ) unless $delflag;
433     foreach my $element ( sort { lc( $shelflist->{$a}->{'shelfname'} ) cmp lc( $shelflist->{$b}->{'shelfname'} ) } keys %$shelflist ) {
434         my %line;
435         $shelflist->{$element}->{shelf} = $element;
436         my $category  = $shelflist->{$element}->{'category'};
437         my $owner     = $shelflist->{$element}->{'owner'}||0;
438         my $canmanage = ShelfPossibleAction( $loggedinuser, $element, 'manage' );
439         $shelflist->{$element}->{"viewcategory$category"} = 1;
440         $shelflist->{$element}->{manageshelf} = $canmanage;
441         if($canmanage || ($loggedinuser && $owner==$loggedinuser)) {
442             $shelflist->{$element}->{'mine'} = 1;
443         }
444         my $member = GetMember( 'borrowernumber' => $owner );
445         $shelflist->{$element}->{ownername} = defined($member) ? $member->{firstname} . " " . $member->{surname} : '';
446         $numberCanManage++ if $canmanage;    # possibly outmoded
447         if ( $shelflist->{$element}->{'category'} eq '1' ) {
448             $shelflist->{$element}->{shares} = IsSharedList($element);
449             push( @shelveslooppriv, $shelflist->{$element} );
450         } else {
451             push( @shelvesloop, $shelflist->{$element} );
452         }
453     }
454
455     my $url = $type eq 'opac' ? "/cgi-bin/koha/opac-shelves.pl" : "/cgi-bin/koha/virtualshelves/shelves.pl";
456     my %qhash = ();
457     foreach (qw(display viewshelf sortfield sort direction)) {
458         $qhash{$_} = $query->param($_) if $query->param($_);
459     }
460     ( scalar keys %qhash ) and $url .= '?' . join '&', map { "$_=$qhash{$_}" } keys %qhash;
461     if ( $shelfnumber && $totitems ) {
462         $template->param(  pagination_bar => pagination_bar( $url, ( int( $totitems / $shelflimit ) ) + ( ( $totitems % $shelflimit ) > 0 ? 1 : 0 ), $itemoff, "itemoff" )  );
463     } elsif ( $totshelves ) {
464         $template->param(
465              pagination_bar => pagination_bar( $url, ( int( $totshelves / $shelveslimit ) ) + ( ( $totshelves % $shelveslimit ) > 0 ? 1 : 0 ), $shelfoff, "shelfoff" )  );
466     }
467     $template->param(
468         shelveslooppriv                                                    => \@shelveslooppriv,
469         shelvesloop                                                        => \@shelvesloop,
470         shelvesloopall                                                     => [ ( @shelvesloop, @shelveslooppriv ) ],
471         numberCanManage                                                    => $numberCanManage,
472         "BiblioDefaultView" . C4::Context->preference("BiblioDefaultView") => 1,
473         csv_profiles                                                       => GetCsvProfilesLoop('marc')
474     );
475     if (   $shelfnumber
476         or $shelves
477         or $edit ) {
478         $template->param( vseflag => 1 );
479     }
480     if ($shelves or    # note: this part looks duplicative, but is intentional
481         $edit
482       ) {
483         $template->param( seflag => 1 );
484         #This hack is just another argument for refactoring this script one day
485         #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
486         $template->param( allow_add => 0, allow_delete_own => 1, allow_delete_other => 0) unless $shelfnumber;
487     }
488
489 #Next call updates the shelves for the Lists button.
490 #May not always be needed (when nothing changed), but doesn't take much.
491     my ($total, $pubshelves, $barshelves) = C4::VirtualShelves::GetSomeShelfNames($loggedinuser, 'MASTHEAD');
492     $template->param(
493             barshelves     => $total->{bartotal},
494             barshelvesloop => $barshelves,
495             pubshelves     => $total->{pubtotal},
496             pubshelvesloop => $pubshelves,
497     );
498
499     output_html_with_http_headers $query, $cookie, $template->output;
500 }
501
502 1;
503 __END__
504
505 =head1 NAME
506
507 VirtualShelves/Page.pm
508
509 =head1 DESCRIPTION
510
511 Module used for both OPAC and intranet pages.
512
513 =head1 CGI PARAMETERS
514
515 =over 4
516
517 =item C<modifyshelfcontents>
518
519 If this script has to modify the shelf content.
520
521 =item C<shelfnumber>
522
523 To know on which shelf to work.
524
525 =item C<addbarcode>
526
527 =item C<op>
528
529  Op can be:
530     * modif: show the template allowing modification of the shelves;
531     * modifsave: save changes from modif mode.
532
533 =item C<viewshelf>
534
535 Load template with 'viewshelves param' displaying the shelf's information.
536
537 =item C<shelves>
538
539 If the param shelves == 1, then add or delete a shelf.
540
541 =item C<addshelf>
542
543 If the param shelves == 1, then addshelf is the name of the shelf to add.
544
545 =back
546
547 =cut