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