Bug 13990: (QA follow-up) Add unit test coverage
[koha.git] / opac / opac-tags.pl
blob267c3c024993cab98d5ac6e39d42af671a35edd1
1 #!/usr/bin/perl
3 # Copyright 2000-2002 Katipo Communications
5 # This file is part of Koha.
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.
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.
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>.
21 =head1 NAME
23 opac-tags.pl
25 =head1 DESCRIPTION
27 TODO :: Description here
29 C4::Scrubber is used to remove all markup content from the sumitted text.
31 =cut
33 use Modern::Perl;
35 use CGI qw ( -utf8 );
36 use CGI::Cookie; # need to check cookies before having CGI parse the POST request
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 use C4::XSLT;
47 use Data::Dumper;
49 use Koha::Biblios;
51 my %newtags = ();
52 my @deltags = ();
53 my %counts = ();
54 my @errors = ();
55 my $perBibResults = {};
57 # Indexes of @errors that do not apply to a particular biblionumber.
58 my @globalErrorIndexes = ();
60 sub ajax_auth_cgi { # returns CGI object
61 my $needed_flags = shift;
62 my %cookies = CGI::Cookie->fetch;
63 my $input = CGI->new;
64 my $sessid = $cookies{'CGISESSID'}->value;
65 my ($auth_status, $auth_sessid) = check_cookie_auth($sessid, $needed_flags);
66 $debug and
67 print STDERR "($auth_status, $auth_sessid) = check_cookie_auth($sessid," . Dumper($needed_flags) . ")\n";
68 if ($auth_status ne "ok") {
69 output_with_http_headers $input, undef,
70 "window.alert('Your CGI session cookie ($sessid) is not current. " .
71 "Please refresh the page and try again.');\n", 'js';
72 exit 0;
74 $debug and print STDERR "AJAX request: " . Dumper($input),
75 "\n(\$auth_status,\$auth_sessid) = ($auth_status,$auth_sessid)\n";
76 return $input;
79 # The trick here is to support multiple tags added to multiple bilbios in one POST.
80 # The HTML might not use this, but it makes it more web-servicey from the start.
81 # So the name of param has to have biblionumber built in.
82 # For lack of anything more compelling, we just use "newtag[biblionumber]"
83 # We split the value into tags at comma and semicolon
85 my $is_ajax = is_ajax();
86 my $openadds = C4::Context->preference('TagsModeration') ? 0 : 1;
87 my $query = ($is_ajax) ? &ajax_auth_cgi({}) : CGI->new();
88 unless (C4::Context->preference('TagsEnabled')) {
89 push @errors, {+ tagsdisabled=>1 };
90 push @globalErrorIndexes, $#errors;
91 } else {
92 foreach ($query->param) {
93 if (/^newtag(.*)/) {
94 my $biblionumber = $1;
95 unless ($biblionumber =~ /^\d+$/) {
96 $debug and warn "$_ references non numerical biblionumber '$biblionumber'";
97 push @errors, {+'badparam' => $_ };
98 push @globalErrorIndexes, $#errors;
99 next;
101 $newtags{$biblionumber} = $query->param($_);
102 } elsif (/^del(\d+)$/) {
103 push @deltags, $1;
108 my $add_op = (scalar(keys %newtags) + scalar(@deltags)) ? 1 : 0;
109 my ($template, $loggedinuser, $cookie);
110 if ($is_ajax) {
111 $loggedinuser = C4::Context->userenv->{'number'}; # must occur AFTER auth
112 $debug and print STDERR "op: $loggedinuser\n";
113 } else {
114 ($template, $loggedinuser, $cookie) = get_template_and_user({
115 template_name => "opac-tags.tt",
116 query => $query,
117 type => "opac",
118 authnotrequired => ($add_op ? 0 : 1), # auth required to add tags
119 debug => 1,
123 if ($add_op) {
124 unless ($loggedinuser) {
125 push @errors, {+'login' => 1 };
126 push @globalErrorIndexes, $#errors;
127 %newtags=(); # zero out any attempted additions
128 @deltags=(); # zero out any attempted deletions
132 my $scrubber;
133 my @newtags_keys = (keys %newtags);
134 if (scalar @newtags_keys) {
135 $scrubber = C4::Scrubber->new();
136 foreach my $biblionumber (@newtags_keys) {
137 my $bibResults = {adds=>0, errors=>[]};
138 my @values = split /[;,]/, $newtags{$biblionumber};
139 foreach (@values) {
140 s/^\s*(.+)\s*$/$1/;
141 my $clean_tag = $scrubber->scrub($_);
142 unless ($clean_tag eq $_) {
143 if ($clean_tag =~ /\S/) {
144 push @errors, {scrubbed=>$clean_tag};
145 push @{$bibResults->{errors}}, {scrubbed=>$clean_tag};
146 } else {
147 push @errors, {scrubbed_all_bad=>1};
148 push @{$bibResults->{errors}}, {scrubbed_all_bad=>1};
149 next; # we don't add it if there's nothing left!
152 my $result = ($openadds) ?
153 add_tag($biblionumber,$clean_tag,$loggedinuser,$loggedinuser) : # pre-approved
154 add_tag($biblionumber,$clean_tag,$loggedinuser) ;
155 if ($result) {
156 $counts{$biblionumber}++;
157 $bibResults->{adds}++;
158 } else {
159 push @errors, {failed_add_tag=>$clean_tag};
160 push @{$bibResults->{errors}}, {failed_add_tag=>$clean_tag};
161 $debug and warn "add_tag($biblionumber,$clean_tag,$loggedinuser...) returned bad result (" . (defined $result ? $result : 'UNDEF') .")";
164 $perBibResults->{$biblionumber} = $bibResults;
167 my $dels = 0;
168 foreach (@deltags) {
169 if (remove_tag($_,$loggedinuser)) {
170 $dels++;
171 } else {
172 push @errors, {failed_delete=>$_};
176 if ($is_ajax) {
177 my $sum = 0;
178 foreach (values %counts) {$sum += $_;}
179 my $js_reply = sprintf("response = {\n\tadded: %d,\n\tdeleted: %d,\n\terrors: %d",$sum,$dels,scalar @errors);
181 # If no add attempts were made, flag global errors.
182 if (@globalErrorIndexes) {
183 $js_reply .= ",\n\tglobal_errors: [";
184 my $first = 1;
185 foreach (@globalErrorIndexes) {
186 $js_reply .= "," unless $first;
187 $first = 0;
188 $js_reply .= "\n\t\t$_";
190 $js_reply .= "\n\t]";
193 my $err_string = '';
194 if (scalar @errors) {
195 $err_string = ",\n\talerts: ["; # open response_function
196 my $i = 1;
197 foreach (@errors) {
198 my $key = (keys %$_)[0];
199 $err_string .= "\n\t\t KOHA.Tags.tag_message.$key(\"" . $_->{$key} . '")';
200 if($i < scalar @errors){ $err_string .= ","; }
201 $i++;
203 $err_string .= "\n\t]\n"; # close response_function
206 # Add per-biblionumber results for use on results page
207 my $js_perbib = "";
208 for my $bib (keys %$perBibResults) {
209 my $bibResult = $perBibResults->{$bib};
210 my $js_bibres = ",\n\t$bib: {\n\t\tadded: $bibResult->{adds}";
211 $js_bibres .= ",\n\t\terrors: [";
212 my $i = 0;
213 foreach (@{$bibResult->{errors}}) {
214 $js_bibres .= "," if ($i);
215 my $key = (keys %$_)[0];
216 $js_bibres .= "\n\t\t\t KOHA.Tags.tag_message.$key(\"" . $_->{$key} . '")';
217 $i++;
219 $js_bibres .= "\n\t\t]\n\t}";
220 $js_perbib .= $js_bibres;
223 output_with_http_headers($query, undef, "$js_reply\n$err_string\n$js_perbib\n};", 'js');
224 exit;
227 my $results = [];
228 my $my_tags = [];
230 if ($loggedinuser) {
231 $my_tags = get_tag_rows({borrowernumber=>$loggedinuser});
232 my $my_approved_tags = get_approval_rows({ approved => 1 });
233 foreach my $tag (@$my_tags) {
234 my $biblio = Koha::Biblios->find( $tag->{biblionumber} );
235 my $record = &GetMarcBiblio({ biblionumber => $tag->{biblionumber} });
236 $tag->{subtitle} = GetRecordValue( 'subtitle', $record, GetFrameworkCode( $tag->{biblionumber} ) );
237 $tag->{title} = $biblio->title;
238 $tag->{author} = $biblio->author;
240 my $xslfile = C4::Context->preference('OPACXSLTResultsDisplay');
241 my $lang = $xslfile ? C4::Languages::getlanguage() : undef;
242 my $sysxml = $xslfile ? C4::XSLT::get_xslt_sysprefs() : undef;
244 if ( $xslfile ) {
245 $tag->{XSLTBloc} = XSLTParse4Display(
246 $tag->{ biblionumber }, $record, "OPACXSLTResultsDisplay",
247 1, undef, $sysxml, $xslfile, $lang
251 my $date = $tag->{date_created} || '';
252 $date =~ /\s+(\d{2}\:\d{2}\:\d{2})/;
253 $tag->{time_created_display} = $1;
254 $tag->{approved} = ( grep { $_->{term} eq $tag->{term} and $_->{approved} } @$my_approved_tags );
258 $template->param(tagsview => 1);
260 if ($add_op) {
261 my $adds = 0;
262 for (values %counts) {$adds += $_;}
263 $template->param(
264 add_op => 1,
265 added_count => $adds,
266 deleted_count => $dels,
268 } else {
269 my ($arg,$limit,$mine);
270 my $hardmax = 100; # you might disagree what this value should be, but there definitely should be a max
271 $limit = $query->param('limit') || $hardmax;
272 $mine = $query->param('mine') || 0; # set if the patron want to see only his own tags.
273 ($limit =~ /^\d+$/ and $limit <= $hardmax) or $limit = $hardmax;
274 $template->param(limit => $limit);
275 my $arghash = {approved=>1, limit=>$limit, 'sort'=>'-weight_total'};
276 $arghash->{'borrowernumber'} = $loggedinuser if $mine;
277 # ($openadds) or $arghash->{approved} = 1;
278 if ($arg = $query->param('tag')) {
279 $arghash->{term} = $arg;
280 } elsif ($arg = $query->param('biblionumber')) {
281 $arghash->{biblionumber} = $arg;
283 $results = get_approval_rows($arghash);
284 stratify_tags(10, $results); # work out the differents sizes for things
285 my $count = scalar @$results;
286 $template->param(TAGLOOP_COUNT => $count, mine => $mine);
288 (scalar @errors ) and $template->param(ERRORS => \@errors);
289 my @orderedresult = sort { uc($a->{'term'}) cmp uc($b->{'term'}) } @$results;
290 (scalar @$results) and $template->param(TAGLOOP => \@orderedresult );
291 (scalar @$my_tags) and $template->param(MY_TAGS => $my_tags);
293 output_html_with_http_headers $query, $cookie, $template->output;
294 __END__
296 =head1 EXAMPLE AJAX POST PARAMETERS
298 CGISESSID 7c6288263107beb320f70f78fd767f56
299 newtag396 fire,+<a+href="foobar.html">foobar</a>,+<img+src="foo.jpg"+/>
301 So this request is trying to add 3 tags to biblio #396. The CGISESSID is the same as that the browser would
302 typically communicate using cookies. If it is valid, the server will split the value of "newtag396" and
303 process the components for addition. In this case the intended tags are:
304 fire
305 <a+href="foobar.html">foobar</a>
306 <img src="foo.jpg" />
308 The first tag is acceptable. The second will be scrubbed of markup, resulting in the tag "foobar".
309 The third tag is all markup, and will be rejected.
311 =head1 EXAMPLE AJAX JSON response
313 response = {
314 added: 2,
315 deleted: 0,
316 errors: 2,
317 alerts: [
318 KOHA.Tags.tag_message.scrubbed("foobar"),
319 KOHA.Tags.tag_message.scrubbed_all_bad("1"),
323 =cut