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