Merge remote-tracking branch 'origin/new/bug_7284'
[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 under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along
17 # with Koha; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
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 strict;
34 use warnings;
35 use CGI;
36 use CGI::Cookie; # need to check cookies before having CGI parse the POST request
37
38 use C4::Auth qw(:DEFAULT check_cookie_auth);
39 use C4::Context;
40 use C4::Debug;
41 use C4::Output 3.02 qw(:html :ajax pagination_bar);
42 use C4::Scrubber;
43 use C4::Biblio;
44 use C4::Tags qw(add_tag get_approval_rows get_tag_rows remove_tag);
45
46 my %newtags = ();
47 my @deltags = ();
48 my %counts  = ();
49 my @errors  = ();
50 my $perBibResults = {};
51
52 # Indexes of @errors that do not apply to a particular biblionumber.
53 my @globalErrorIndexes = ();
54
55 sub ajax_auth_cgi ($) {     # returns CGI object
56         my $needed_flags = shift;
57         my %cookies = fetch CGI::Cookie;
58         my $input = CGI->new;
59         my $sessid = $cookies{'CGISESSID'}->value || $input->param('CGISESSID');
60         my ($auth_status, $auth_sessid) = check_cookie_auth($sessid, $needed_flags);
61         $debug and
62         print STDERR "($auth_status, $auth_sessid) = check_cookie_auth($sessid," . Dumper($needed_flags) . ")\n";
63         if ($auth_status ne "ok") {
64                 output_with_http_headers $input, undef,
65                 "window.alert('Your CGI session cookie ($sessid) is not current.  " .
66                 "Please refresh the page and try again.');\n", 'js';
67                 exit 0;
68         }
69         $debug and print STDERR "AJAX request: " . Dumper($input),
70                 "\n(\$auth_status,\$auth_sessid) = ($auth_status,$auth_sessid)\n";
71         return $input;
72 }
73
74 # The trick here is to support multiple tags added to multiple bilbios in one POST.
75 # The HTML might not use this, but it makes it more web-servicey from the start.
76 # So the name of param has to have biblionumber built in.
77 # For lack of anything more compelling, we just use "newtag[biblionumber]"
78 # We split the value into tags at comma and semicolon
79
80 my $is_ajax = is_ajax();
81 my $openadds = C4::Context->preference('TagsModeration') ? 0 : 1;
82 my $query = ($is_ajax) ? &ajax_auth_cgi({}) : CGI->new();
83 unless (C4::Context->preference('TagsEnabled')) {
84         push @errors, {+ tagsdisabled=>1 };
85     push @globalErrorIndexes, $#errors;
86 } else {
87         foreach ($query->param) {
88                 if (/^newtag(.*)/) {
89                         my $biblionumber = $1;
90                         unless ($biblionumber =~ /^\d+$/) {
91                                 $debug and warn "$_ references non numerical biblionumber '$biblionumber'";
92                                 push @errors, {+'badparam' => $_ };
93                 push @globalErrorIndexes, $#errors;
94                                 next;
95                         }
96                         $newtags{$biblionumber} = $query->param($_);
97                 } elsif (/^del(\d+)$/) {
98                         push @deltags, $1;
99                 }
100         }
101 }
102
103 my $add_op = (scalar(keys %newtags) + scalar(@deltags)) ? 1 : 0;
104 my ($template, $loggedinuser, $cookie);
105 if ($is_ajax) {
106         $loggedinuser = C4::Context->userenv->{'number'};  # must occur AFTER auth
107         $debug and print STDERR "op: $loggedinuser\n";
108 } else {
109         ($template, $loggedinuser, $cookie) = get_template_and_user({
110                 template_name   => "opac-tags.tmpl",
111                 query           => $query,
112                 type            => "opac",
113                 authnotrequired => ($add_op ? 0 : 1),   # auth required to add tags
114                 debug           => 1,
115         });
116 }
117
118 if ($add_op) {
119         unless ($loggedinuser) {
120                 push @errors, {+'login' => 1 };
121         push @globalErrorIndexes, $#errors;
122                 %newtags=();    # zero out any attempted additions
123                 @deltags=();    # zero out any attempted deletions
124         }
125 }
126
127 my $scrubber;
128 my @newtags_keys = (keys %newtags);
129 if (scalar @newtags_keys) {
130         $scrubber = C4::Scrubber->new();
131         foreach my $biblionumber (@newtags_keys) {
132         my $bibResults = {adds=>0, errors=>[]};
133                 my @values = split /[;,]/, $newtags{$biblionumber};
134                 foreach (@values) {
135                         s/^\s*(.+)\s*$/$1/;
136                         my $clean_tag = $scrubber->scrub($_);
137                         unless ($clean_tag eq $_) {
138                                 if ($clean_tag =~ /\S/) {
139                                         push @errors, {scrubbed=>$clean_tag};
140                                         push @{$bibResults->{errors}}, {scrubbed=>$clean_tag};
141                                 } else {
142                                         push @errors, {scrubbed_all_bad=>1};
143                                         push @{$bibResults->{errors}}, {scrubbed_all_bad=>1};
144                                         next;   # we don't add it if there's nothing left!
145                                 }
146                         }
147                         my $result = ($openadds) ?
148                                 add_tag($biblionumber,$clean_tag,$loggedinuser,$loggedinuser) : # pre-approved
149                                 add_tag($biblionumber,$clean_tag,$loggedinuser)   ;
150                         if ($result) {
151                                 $counts{$biblionumber}++;
152                 $bibResults->{adds}++;
153                         } else {
154                                 push @errors, {failed_add_tag=>$clean_tag};
155                                 push @{$bibResults->{errors}}, {failed_add_tag=>$clean_tag};
156                                 $debug and warn "add_tag($biblionumber,$clean_tag,$loggedinuser...) returned bad result (" . (defined $result ? $result : 'UNDEF') .")";
157                         }
158                 }
159         $perBibResults->{$biblionumber} = $bibResults;
160         }
161 }
162 my $dels = 0;
163 foreach (@deltags) {
164         if (remove_tag($_,$loggedinuser)) {
165                 $dels++;
166         } else {
167                 push @errors, {failed_delete=>$_};
168         }
169 }
170
171 if ($is_ajax) {
172         my $sum = 0;
173         foreach (values %counts) {$sum += $_;}
174         my $js_reply = sprintf("response = {\n\tadded: %d,\n\tdeleted: %d,\n\terrors: %d",$sum,$dels,scalar @errors);
175
176     # If no add attempts were made, flag global errors.
177     if (@globalErrorIndexes) {
178         $js_reply .= ",\n\tglobal_errors: [";
179         my $first = 1;
180         foreach (@globalErrorIndexes) {
181             $js_reply .= "," unless $first;
182             $first = 0;
183             $js_reply .= "\n\t\t$_";
184         }
185         $js_reply .= "\n\t]";
186     }
187     
188         my $err_string = '';
189         if (scalar @errors) {
190                 $err_string = ",\n\talerts: ["; # open response_function
191                 my $i = 1;
192                 foreach (@errors) {
193                         my $key = (keys %$_)[0];
194                         $err_string .= "\n\t\t KOHA.Tags.tag_message.$key(\"" . $_->{$key} . '")';
195                         if($i < scalar @errors){ $err_string .= ","; }
196                         $i++;
197                 }
198                 $err_string .= "\n\t]\n";       # close response_function
199         }
200
201     # Add per-biblionumber results for use on results page
202     my $js_perbib = "";
203     for my $bib (keys %$perBibResults) {
204         my $bibResult = $perBibResults->{$bib};
205         my $js_bibres = ",\n\t$bib: {\n\t\tadded: $bibResult->{adds}";
206         $js_bibres .= ",\n\t\terrors: [";
207         my $i = 0;
208         foreach (@{$bibResult->{errors}}) {
209             $js_bibres .= "," if ($i);
210                         my $key = (keys %$_)[0];
211                         $js_bibres .= "\n\t\t\t KOHA.Tags.tag_message.$key(\"" . $_->{$key} . '")';
212             $i++;
213         }
214         $js_bibres .= "\n\t\t]\n\t}";
215         $js_perbib .= $js_bibres;
216     }
217
218         output_with_http_headers($query, undef, "$js_reply\n$err_string\n$js_perbib\n};", 'js');
219         exit;
220 }
221
222 my $results = [];
223 my $my_tags = [];
224
225 if ($loggedinuser) {
226         $my_tags = get_tag_rows({borrowernumber=>$loggedinuser});
227         foreach (@$my_tags) {
228                 my $biblio = GetBiblioData($_->{biblionumber});
229                 $_->{bib_summary} = $biblio->{title}; 
230                 ($biblio->{author}) and $_->{bib_summary} .= " by " . $biblio->{author};
231                 my $date = $_->{date_created} || '';
232                 $date =~ /\s+(\d{2}\:\d{2}\:\d{2})/;
233                 $_->{time_created_display} = $1;
234         }
235 }
236
237 $template->param(tagsview => 1,
238 dateformat => C4::Context->preference("dateformat"));
239
240 if ($add_op) {
241         my $adds = 0;
242         for (values %counts) {$adds += $_;}
243         $template->param(
244                 add_op => 1,
245                 added_count => $adds,
246                 deleted_count => $dels,
247         );
248 } else {
249         my ($arg,$limit,$mine);
250         my $hardmax = 100;      # you might disagree what this value should be, but there definitely should be a max
251         $limit = $query->param('limit') || $hardmax;
252     $mine =  $query->param('mine') || 0; # set if the patron want to see only his own tags.
253         ($limit =~ /^\d+$/ and $limit <= $hardmax) or $limit = $hardmax;
254         $template->param(limit => $limit);
255         my $arghash = {approved=>1, limit=>$limit, 'sort'=>'-weight_total'};
256     $arghash->{'borrowernumber'} = $loggedinuser if $mine;
257         # ($openadds) or $arghash->{approved} = 1;
258         if ($arg = $query->param('tag')) {
259                 $arghash->{term} = $arg;
260         } elsif ($arg = $query->param('biblionumber')) {
261                 $arghash->{biblionumber} = $arg;
262         }
263         $results = get_approval_rows($arghash);
264
265         my $count = scalar @$results;
266         $template->param(TAGLOOP_COUNT => $count, mine => $mine);
267         # Here we make a halfhearted attempt to separate the tags into "strata" based on weight_total
268         # FIXME: code4lib probably has a better algorithm, iirc
269         # FIXME: when we get a better algorithm, move to C4
270         my $maxstrata = 5;
271         my $strata = 1;
272         my $previous = 0;
273         my $chunk = ($count/$maxstrata)/2;
274         my $total = 0;
275         my %cloud;
276         foreach (reverse @$results) {
277                 my $current = $_->{weight_total};
278                 $total++;
279                 $cloud{$strata}++;
280                 if ($current == $previous) {
281                         $_->{cloudweight} = $strata;
282                         next;
283                 } 
284                 if ($strata < $maxstrata and 
285                         ($cloud{$strata} > $chunk or 
286                         $count-$total <= $maxstrata-$strata)) {
287                         $strata++;
288                 }
289                 $_->{cloudweight} = $strata;
290                 $previous = $current;
291         }
292 }
293 (scalar @errors  ) and $template->param(ERRORS  => \@errors);
294 my @orderedresult = sort { uc($a->{'term'}) cmp uc($b->{'term'}) } @$results;
295 (scalar @$results) and $template->param(TAGLOOP => \@orderedresult );
296 (scalar @$my_tags) and $template->param(MY_TAGS => $my_tags);
297
298 output_html_with_http_headers $query, $cookie, $template->output;
299 __END__
300
301 =head1 EXAMPLE AJAX POST PARAMETERS
302
303 CGISESSID       7c6288263107beb320f70f78fd767f56
304 newtag396       fire,+<a+href="foobar.html">foobar</a>,+<img+src="foo.jpg"+/>
305
306 So this request is trying to add 3 tags to biblio #396.  The CGISESSID is the same as that the browser would
307 typically communicate using cookies.  If it is valid, the server will split the value of "newtag396" and 
308 process the components for addition.  In this case the intended tags are:
309         fire
310         <a+href="foobar.html">foobar</a>
311         <img src="foo.jpg" />
312
313 The first tag is acceptable.  The second will be scrubbed of markup, resulting in the tag "foobar".  
314 The third tag is all markup, and will be rejected.  
315
316 =head1 EXAMPLE AJAX JSON response
317
318 response = {
319         added: 2,
320         deleted: 0,
321         errors: 2,
322         alerts: [
323                  KOHA.Tags.tag_message.scrubbed("foobar"),
324                  KOHA.Tags.tag_message.scrubbed_all_bad("1"),
325         ],
326 };
327
328 =cut
329