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