Bug 29697: Remove GetHiddenItemnumbers
[koha.git] / opac / opac-tags.pl
1 #!/usr/bin/perl
2
3 # Copyright 2000-2002 Katipo Communications
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20
21 =head1 NAME
22
23 opac-tags.pl
24
25 =head1 DESCRIPTION
26
27 TODO :: Description here
28
29 C4::Scrubber is used to remove all markup content from the sumitted text.
30
31 =cut
32
33 use Modern::Perl;
34
35 use CGI qw ( -utf8 );
36 use CGI::Cookie; # need to check cookies before having CGI parse the POST request
37 use Array::Utils qw( array_minus );
38
39 use C4::Auth qw( check_cookie_auth get_template_and_user );
40 use C4::Context;
41 use C4::Output qw( output_with_http_headers is_ajax output_html_with_http_headers );
42 use C4::Scrubber;
43 use C4::Biblio qw( GetMarcBiblio );
44 use C4::Items qw( GetItemsInfo );
45 use C4::Tags qw(
46     add_tag
47     get_approval_rows
48     get_tag_rows
49     remove_tag
50     stratify_tags
51 );
52 use C4::XSLT qw( XSLTParse4Display );
53
54
55 use Koha::Logger;
56 use Koha::Biblios;
57 use Koha::CirculationRules;
58
59 my %newtags = ();
60 my @deltags = ();
61 my %counts  = ();
62 my @errors  = ();
63 my $perBibResults = {};
64
65 # Indexes of @errors that do not apply to a particular biblionumber.
66 my @globalErrorIndexes = ();
67
68 sub ajax_auth_cgi {     # returns CGI object
69         my $needed_flags = shift;
70     my %cookies = CGI::Cookie->fetch;
71         my $input = CGI->new;
72     my $sessid = $cookies{'CGISESSID'}->value;
73     my ($auth_status) = check_cookie_auth($sessid, $needed_flags);
74         if ($auth_status ne "ok") {
75                 output_with_http_headers $input, undef,
76                 "window.alert('Your CGI session cookie ($sessid) is not current.  " .
77                 "Please refresh the page and try again.');\n", 'js';
78                 exit 0;
79         }
80         return $input;
81 }
82
83 # The trick here is to support multiple tags added to multiple bilbios in one POST.
84 # The HTML might not use this, but it makes it more web-servicey from the start.
85 # So the name of param has to have biblionumber built in.
86 # For lack of anything more compelling, we just use "newtag[biblionumber]"
87 # We split the value into tags at comma and semicolon
88
89 my $is_ajax = is_ajax();
90 my $openadds = C4::Context->preference('TagsModeration') ? 0 : 1;
91 my $query = ($is_ajax) ? &ajax_auth_cgi({}) : CGI->new();
92 foreach ($query->param) {
93     if (/^newtag(.*)/) {
94         my $biblionumber = $1;
95         unless ($biblionumber =~ /^\d+$/) {
96             push @errors, {+'badparam' => $_ };
97             push @globalErrorIndexes, $#errors;
98             next;
99         }
100         $newtags{$biblionumber} = $query->param($_);
101     } elsif (/^del(\d+)$/) {
102         push @deltags, $1;
103     }
104 }
105
106 my $add_op = (scalar(keys %newtags) + scalar(@deltags)) ? 1 : 0;
107 my ($template, $loggedinuser, $cookie);
108 if ($is_ajax) {
109         $loggedinuser = C4::Context->userenv->{'number'};  # must occur AFTER auth
110 } else {
111         ($template, $loggedinuser, $cookie) = get_template_and_user({
112         template_name   => "opac-tags.tt",
113         query           => $query,
114         type            => "opac",
115         authnotrequired => ($add_op ? 0 : 1), # auth required to add tags
116         });
117 }
118
119 unless ( C4::Context->preference('TagsEnabled') ) {
120     print $query->redirect("/cgi-bin/koha/errors/404.pl");
121     exit;
122 }
123
124 if ($add_op) {
125         unless ($loggedinuser) {
126                 push @errors, {+'login' => 1 };
127         push @globalErrorIndexes, $#errors;
128                 %newtags=();    # zero out any attempted additions
129                 @deltags=();    # zero out any attempted deletions
130         }
131 }
132
133 my $scrubber;
134 my @newtags_keys = (keys %newtags);
135 if (scalar @newtags_keys) {
136         $scrubber = C4::Scrubber->new();
137         foreach my $biblionumber (@newtags_keys) {
138         my $bibResults = {adds=>0, errors=>[]};
139                 my @values = split /[;,]/, $newtags{$biblionumber};
140                 foreach (@values) {
141                         s/^\s*(.+)\s*$/$1/;
142                         my $clean_tag = $scrubber->scrub($_);
143                         unless ($clean_tag eq $_) {
144                                 if ($clean_tag =~ /\S/) {
145                                         push @errors, {scrubbed=>$clean_tag};
146                                         push @{$bibResults->{errors}}, {scrubbed=>$clean_tag};
147                                 } else {
148                                         push @errors, {scrubbed_all_bad=>1};
149                                         push @{$bibResults->{errors}}, {scrubbed_all_bad=>1};
150                                         next;   # we don't add it if there's nothing left!
151                                 }
152                         }
153                         my $result = ($openadds) ?
154                                 add_tag($biblionumber,$clean_tag,$loggedinuser,$loggedinuser) : # pre-approved
155                                 add_tag($biblionumber,$clean_tag,$loggedinuser)   ;
156                         if ($result) {
157                                 $counts{$biblionumber}++;
158                 $bibResults->{adds}++;
159                         } else {
160                                 push @errors, {failed_add_tag=>$clean_tag};
161                                 push @{$bibResults->{errors}}, {failed_add_tag=>$clean_tag};
162                 Koha::Logger->get->warn("add_tag($biblionumber,$clean_tag,$loggedinuser...) returned bad result (" . (defined $result ? $result : 'UNDEF') .")");
163                         }
164                 }
165         $perBibResults->{$biblionumber} = $bibResults;
166         }
167 }
168 my $dels = 0;
169 foreach (@deltags) {
170         if (remove_tag($_,$loggedinuser)) {
171                 $dels++;
172         } else {
173                 push @errors, {failed_delete=>$_};
174         }
175 }
176
177 if ($is_ajax) {
178         my $sum = 0;
179         foreach (values %counts) {$sum += $_;}
180         my $js_reply = sprintf("response = {\n\tadded: %d,\n\tdeleted: %d,\n\terrors: %d",$sum,$dels,scalar @errors);
181
182     # If no add attempts were made, flag global errors.
183     if (@globalErrorIndexes) {
184         $js_reply .= ",\n\tglobal_errors: [";
185         my $first = 1;
186         foreach (@globalErrorIndexes) {
187             $js_reply .= "," unless $first;
188             $first = 0;
189             $js_reply .= "\n\t\t$_";
190         }
191         $js_reply .= "\n\t]";
192     }
193     
194         my $err_string = '';
195         if (scalar @errors) {
196                 $err_string = ",\n\talerts: ["; # open response_function
197                 my $i = 1;
198                 foreach (@errors) {
199                         my $key = (keys %$_)[0];
200                         $err_string .= "\n\t\t KOHA.Tags.tag_message.$key(\"" . $_->{$key} . '")';
201                         if($i < scalar @errors){ $err_string .= ","; }
202                         $i++;
203                 }
204                 $err_string .= "\n\t]\n";       # close response_function
205         }
206
207     # Add per-biblionumber results for use on results page
208     my $js_perbib = "";
209     for my $bib (keys %$perBibResults) {
210         my $bibResult = $perBibResults->{$bib};
211         my $js_bibres = ",\n\t$bib: {\n\t\tadded: $bibResult->{adds}";
212         $js_bibres .= ",\n\t\terrors: [";
213         my $i = 0;
214         foreach (@{$bibResult->{errors}}) {
215             $js_bibres .= "," if ($i);
216                         my $key = (keys %$_)[0];
217                         $js_bibres .= "\n\t\t\t KOHA.Tags.tag_message.$key(\"" . $_->{$key} . '")';
218             $i++;
219         }
220         $js_bibres .= "\n\t\t]\n\t}";
221         $js_perbib .= $js_bibres;
222     }
223
224         output_with_http_headers($query, undef, "$js_reply\n$err_string\n$js_perbib\n};", 'js');
225         exit;
226 }
227
228 my $results = [];
229 my $my_tags = [];
230
231 if ($loggedinuser) {
232     my $patron = Koha::Patrons->find( { borrowernumber => $loggedinuser } );
233     $borcat = $patron ? $patron->categorycode : $borcat;
234     my $rules = C4::Context->yaml_preference('OpacHiddenItems');
235     my $should_hide = ( $rules ) ? 1 : 0;
236     $my_tags = get_tag_rows({borrowernumber=>$loggedinuser});
237     my $my_approved_tags = get_approval_rows({ approved => 1 });
238
239     my $art_req_itypes;
240     if( C4::Context->preference('ArticleRequests') ) {
241         $art_req_itypes = Koha::CirculationRules->guess_article_requestable_itemtypes({ $patron ? ( categorycode => $patron->categorycode ) : () });
242     }
243
244     # get biblionumbers stored in the cart
245     my @cart_list;
246
247     if($query->cookie("bib_list")){
248         my $cart_list = $query->cookie("bib_list");
249         @cart_list = split(/\//, $cart_list);
250     }
251
252     foreach my $tag (@$my_tags) {
253         $tag->{visible} = 0;
254         my $biblio = Koha::Biblios->find( $tag->{biblionumber} );
255         my $record = &GetMarcBiblio({
256             biblionumber => $tag->{biblionumber},
257             embed_items  => 1,
258             opac         => 1,
259             borcat       => $borcat });
260         next unless $record;
261         my @hidden_items;
262         if ($should_hide) {
263             my $items = $biblio->items;
264             my @all_itemnumbers = $items->get_column('itemnumber');
265             my @items_to_show = $items->filter_by_visible_in_opac({ opac => 1, patron => $patron })->as_list;
266             @hidden_items = array_minus( @all_itemnumbers, @items_to_show );
267         }
268         next
269           if (
270             (
271                 !$patron
272                 or ( $patron and !$patron->category->override_hidden_items )
273             )
274             and $biblio->hidden_in_opac( { rules => $rules } )
275           );
276         $tag->{title} = $biblio->title;
277         $tag->{subtitle} = $biblio->subtitle;
278         $tag->{medium} = $biblio->medium;
279         $tag->{part_number} = $biblio->part_number;
280         $tag->{part_name} = $biblio->part_name;
281         $tag->{author} = $biblio->author;
282         # BZ17530: 'Intelligent' guess if result can be article requested
283         $tag->{artreqpossible} = ( $art_req_itypes->{ $tag->{itemtype} // q{} } || $art_req_itypes->{ '*' } ) ? 1 : q{};
284
285         my $variables = {
286             anonymous_session => ($loggedinuser) ? 0 : 1
287         };
288         $tag->{XSLTBloc} = XSLTParse4Display(
289             {
290                 biblionumber   => $tag->{biblionumber},
291                 record         => $record,
292                 xsl_syspref    => 'OPACXSLTResultsDisplay',
293                 fix_amps       => 1,
294                 hidden_items   => \@hidden_items,
295                 xslt_variables => $variables
296             }
297         );
298
299         my $date = $tag->{date_created} || '';
300         $date =~ /\s+(\d{2}\:\d{2}\:\d{2})/;
301         $tag->{time_created_display} = $1;
302         $tag->{approved} = ( grep { $_->{term} eq $tag->{term} and $_->{approved} } @$my_approved_tags );
303         $tag->{visible} = 1;
304         # while we're checking each line, see if item is in the cart
305         if ( grep {$_ eq $biblio->biblionumber} @cart_list) {
306             $tag->{incart} = 1;
307         }
308     }
309 }
310
311 $template->param(tagsview => 1);
312
313 if ($add_op) {
314         my $adds = 0;
315         for (values %counts) {$adds += $_;}
316         $template->param(
317                 add_op => 1,
318                 added_count => $adds,
319                 deleted_count => $dels,
320         );
321 } else {
322         my ($arg,$limit,$mine);
323         my $hardmax = 100;      # you might disagree what this value should be, but there definitely should be a max
324         $limit = $query->param('limit') || $hardmax;
325     $mine =  $query->param('mine') || 0; # set if the patron want to see only his own tags.
326         ($limit =~ /^\d+$/ and $limit <= $hardmax) or $limit = $hardmax;
327         $template->param(limit => $limit);
328         my $arghash = {approved=>1, limit=>$limit, 'sort'=>'-weight_total'};
329     $arghash->{'borrowernumber'} = $loggedinuser if $mine;
330         # ($openadds) or $arghash->{approved} = 1;
331         if ($arg = $query->param('tag')) {
332                 $arghash->{term} = $arg;
333         } elsif ($arg = $query->param('biblionumber')) {
334                 $arghash->{biblionumber} = $arg;
335         }
336         $results = get_approval_rows($arghash);
337     stratify_tags(10, $results); # work out the differents sizes for things
338         my $count = scalar @$results;
339         $template->param(TAGLOOP_COUNT => $count, mine => $mine);
340 }
341 (scalar @errors  ) and $template->param(ERRORS  => \@errors);
342 my @orderedresult = sort { uc($a->{'term'}) cmp uc($b->{'term'}) } @$results;
343 (scalar @$results) and $template->param(TAGLOOP => \@orderedresult );
344 (scalar @$my_tags) and $template->param(MY_TAGS => $my_tags);
345
346 output_html_with_http_headers $query, $cookie, $template->output;
347 __END__
348
349 =head1 EXAMPLE AJAX POST PARAMETERS
350
351 CGISESSID       7c6288263107beb320f70f78fd767f56
352 newtag396       fire,+<a+href="foobar.html">foobar</a>,+<img+src="foo.jpg"+/>
353
354 So this request is trying to add 3 tags to biblio #396.  The CGISESSID is the same as that the browser would
355 typically communicate using cookies.  If it is valid, the server will split the value of "newtag396" and 
356 process the components for addition.  In this case the intended tags are:
357         fire
358         <a+href="foobar.html">foobar</a>
359         <img src="foo.jpg" />
360
361 The first tag is acceptable.  The second will be scrubbed of markup, resulting in the tag "foobar".  
362 The third tag is all markup, and will be rejected.  
363
364 =head1 EXAMPLE AJAX JSON response
365
366 response = {
367         added: 2,
368         deleted: 0,
369         errors: 2,
370         alerts: [
371                  KOHA.Tags.tag_message.scrubbed("foobar"),
372                  KOHA.Tags.tag_message.scrubbed_all_bad("1"),
373         ],
374 };
375
376 =cut
377