Bug 19893: Support for joined subfields in mappings
[koha.git] / opac / opac-tags.pl
blob272d896f2367e738f67f29b479fefb36f552b39f
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::Items qw(GetItemsInfo GetHiddenItemnumbers);
45 use C4::Tags qw(add_tag get_approval_rows get_tag_rows remove_tag stratify_tags);
46 use C4::XSLT;
48 use Data::Dumper;
50 use Koha::Biblios;
52 my %newtags = ();
53 my @deltags = ();
54 my %counts = ();
55 my @errors = ();
56 my $perBibResults = {};
58 # Indexes of @errors that do not apply to a particular biblionumber.
59 my @globalErrorIndexes = ();
61 sub ajax_auth_cgi { # returns CGI object
62 my $needed_flags = shift;
63 my %cookies = CGI::Cookie->fetch;
64 my $input = CGI->new;
65 my $sessid = $cookies{'CGISESSID'}->value;
66 my ($auth_status, $auth_sessid) = check_cookie_auth($sessid, $needed_flags);
67 $debug and
68 print STDERR "($auth_status, $auth_sessid) = check_cookie_auth($sessid," . Dumper($needed_flags) . ")\n";
69 if ($auth_status ne "ok") {
70 output_with_http_headers $input, undef,
71 "window.alert('Your CGI session cookie ($sessid) is not current. " .
72 "Please refresh the page and try again.');\n", 'js';
73 exit 0;
75 $debug and print STDERR "AJAX request: " . Dumper($input),
76 "\n(\$auth_status,\$auth_sessid) = ($auth_status,$auth_sessid)\n";
77 return $input;
80 # The trick here is to support multiple tags added to multiple bilbios in one POST.
81 # The HTML might not use this, but it makes it more web-servicey from the start.
82 # So the name of param has to have biblionumber built in.
83 # For lack of anything more compelling, we just use "newtag[biblionumber]"
84 # We split the value into tags at comma and semicolon
86 my $is_ajax = is_ajax();
87 my $openadds = C4::Context->preference('TagsModeration') ? 0 : 1;
88 my $query = ($is_ajax) ? &ajax_auth_cgi({}) : CGI->new();
89 unless (C4::Context->preference('TagsEnabled')) {
90 push @errors, {+ tagsdisabled=>1 };
91 push @globalErrorIndexes, $#errors;
92 } else {
93 foreach ($query->param) {
94 if (/^newtag(.*)/) {
95 my $biblionumber = $1;
96 unless ($biblionumber =~ /^\d+$/) {
97 $debug and warn "$_ references non numerical biblionumber '$biblionumber'";
98 push @errors, {+'badparam' => $_ };
99 push @globalErrorIndexes, $#errors;
100 next;
102 $newtags{$biblionumber} = $query->param($_);
103 } elsif (/^del(\d+)$/) {
104 push @deltags, $1;
109 my $add_op = (scalar(keys %newtags) + scalar(@deltags)) ? 1 : 0;
110 my ($template, $loggedinuser, $cookie);
111 if ($is_ajax) {
112 $loggedinuser = C4::Context->userenv->{'number'}; # must occur AFTER auth
113 $debug and print STDERR "op: $loggedinuser\n";
114 } else {
115 ($template, $loggedinuser, $cookie) = get_template_and_user({
116 template_name => "opac-tags.tt",
117 query => $query,
118 type => "opac",
119 authnotrequired => ($add_op ? 0 : 1), # auth required to add tags
120 debug => 1,
124 if ($add_op) {
125 unless ($loggedinuser) {
126 push @errors, {+'login' => 1 };
127 push @globalErrorIndexes, $#errors;
128 %newtags=(); # zero out any attempted additions
129 @deltags=(); # zero out any attempted deletions
133 my $scrubber;
134 my @newtags_keys = (keys %newtags);
135 if (scalar @newtags_keys) {
136 $scrubber = C4::Scrubber->new();
137 foreach my $biblionumber (@newtags_keys) {
138 my $bibResults = {adds=>0, errors=>[]};
139 my @values = split /[;,]/, $newtags{$biblionumber};
140 foreach (@values) {
141 s/^\s*(.+)\s*$/$1/;
142 my $clean_tag = $scrubber->scrub($_);
143 unless ($clean_tag eq $_) {
144 if ($clean_tag =~ /\S/) {
145 push @errors, {scrubbed=>$clean_tag};
146 push @{$bibResults->{errors}}, {scrubbed=>$clean_tag};
147 } else {
148 push @errors, {scrubbed_all_bad=>1};
149 push @{$bibResults->{errors}}, {scrubbed_all_bad=>1};
150 next; # we don't add it if there's nothing left!
153 my $result = ($openadds) ?
154 add_tag($biblionumber,$clean_tag,$loggedinuser,$loggedinuser) : # pre-approved
155 add_tag($biblionumber,$clean_tag,$loggedinuser) ;
156 if ($result) {
157 $counts{$biblionumber}++;
158 $bibResults->{adds}++;
159 } else {
160 push @errors, {failed_add_tag=>$clean_tag};
161 push @{$bibResults->{errors}}, {failed_add_tag=>$clean_tag};
162 $debug and warn "add_tag($biblionumber,$clean_tag,$loggedinuser...) returned bad result (" . (defined $result ? $result : 'UNDEF') .")";
165 $perBibResults->{$biblionumber} = $bibResults;
168 my $dels = 0;
169 foreach (@deltags) {
170 if (remove_tag($_,$loggedinuser)) {
171 $dels++;
172 } else {
173 push @errors, {failed_delete=>$_};
177 if ($is_ajax) {
178 my $sum = 0;
179 foreach (values %counts) {$sum += $_;}
180 my $js_reply = sprintf("response = {\n\tadded: %d,\n\tdeleted: %d,\n\terrors: %d",$sum,$dels,scalar @errors);
182 # If no add attempts were made, flag global errors.
183 if (@globalErrorIndexes) {
184 $js_reply .= ",\n\tglobal_errors: [";
185 my $first = 1;
186 foreach (@globalErrorIndexes) {
187 $js_reply .= "," unless $first;
188 $first = 0;
189 $js_reply .= "\n\t\t$_";
191 $js_reply .= "\n\t]";
194 my $err_string = '';
195 if (scalar @errors) {
196 $err_string = ",\n\talerts: ["; # open response_function
197 my $i = 1;
198 foreach (@errors) {
199 my $key = (keys %$_)[0];
200 $err_string .= "\n\t\t KOHA.Tags.tag_message.$key(\"" . $_->{$key} . '")';
201 if($i < scalar @errors){ $err_string .= ","; }
202 $i++;
204 $err_string .= "\n\t]\n"; # close response_function
207 # Add per-biblionumber results for use on results page
208 my $js_perbib = "";
209 for my $bib (keys %$perBibResults) {
210 my $bibResult = $perBibResults->{$bib};
211 my $js_bibres = ",\n\t$bib: {\n\t\tadded: $bibResult->{adds}";
212 $js_bibres .= ",\n\t\terrors: [";
213 my $i = 0;
214 foreach (@{$bibResult->{errors}}) {
215 $js_bibres .= "," if ($i);
216 my $key = (keys %$_)[0];
217 $js_bibres .= "\n\t\t\t KOHA.Tags.tag_message.$key(\"" . $_->{$key} . '")';
218 $i++;
220 $js_bibres .= "\n\t\t]\n\t}";
221 $js_perbib .= $js_bibres;
224 output_with_http_headers($query, undef, "$js_reply\n$err_string\n$js_perbib\n};", 'js');
225 exit;
228 my $results = [];
229 my $my_tags = [];
230 my $borcat = q{};
232 if ($loggedinuser) {
233 my $patron = Koha::Patrons->find( { borrowernumber => $loggedinuser } );
234 $borcat = $patron ? $patron->categorycode : $borcat;
235 my $should_hide = C4::Context->preference('OpacHiddenItems') // q{};
236 $should_hide = ( $should_hide =~ /\S/ ) ? 1 : 0;
237 $my_tags = get_tag_rows({borrowernumber=>$loggedinuser});
238 my $my_approved_tags = get_approval_rows({ approved => 1 });
239 foreach my $tag (@$my_tags) {
240 $tag->{visible} = 0;
241 my $biblio = Koha::Biblios->find( $tag->{biblionumber} );
242 my $record = &GetMarcBiblio({
243 biblionumber => $tag->{biblionumber},
244 embed_items => 1,
245 opac => 1,
246 borcat => $borcat });
247 next unless $record;
248 my $hidden_items = undef;
249 my @hidden_itemnumbers;
250 my @all_items;
251 if ($should_hide) {
252 @all_items = GetItemsInfo( $tag->{biblionumber} );
253 @hidden_itemnumbers = GetHiddenItemnumbers({
254 items => \@all_items,
255 borcat => $borcat });
256 $hidden_items = \@hidden_itemnumbers;
258 next if ( $should_hide && scalar @all_items == scalar @hidden_itemnumbers );
259 $tag->{subtitle} = GetRecordValue( 'subtitle', $record, GetFrameworkCode( $tag->{biblionumber} ) );
260 $tag->{title} = $biblio->title;
261 $tag->{author} = $biblio->author;
263 my $xslfile = C4::Context->preference('OPACXSLTResultsDisplay');
264 my $lang = $xslfile ? C4::Languages::getlanguage() : undef;
265 my $sysxml = $xslfile ? C4::XSLT::get_xslt_sysprefs() : undef;
267 if ( $xslfile ) {
268 $tag->{XSLTBloc} = XSLTParse4Display(
269 $tag->{ biblionumber }, $record, "OPACXSLTResultsDisplay",
270 1, $hidden_items, $sysxml, $xslfile, $lang
274 my $date = $tag->{date_created} || '';
275 $date =~ /\s+(\d{2}\:\d{2}\:\d{2})/;
276 $tag->{time_created_display} = $1;
277 $tag->{approved} = ( grep { $_->{term} eq $tag->{term} and $_->{approved} } @$my_approved_tags );
278 $tag->{visible} = 1;
282 $template->param(tagsview => 1);
284 if ($add_op) {
285 my $adds = 0;
286 for (values %counts) {$adds += $_;}
287 $template->param(
288 add_op => 1,
289 added_count => $adds,
290 deleted_count => $dels,
292 } else {
293 my ($arg,$limit,$mine);
294 my $hardmax = 100; # you might disagree what this value should be, but there definitely should be a max
295 $limit = $query->param('limit') || $hardmax;
296 $mine = $query->param('mine') || 0; # set if the patron want to see only his own tags.
297 ($limit =~ /^\d+$/ and $limit <= $hardmax) or $limit = $hardmax;
298 $template->param(limit => $limit);
299 my $arghash = {approved=>1, limit=>$limit, 'sort'=>'-weight_total'};
300 $arghash->{'borrowernumber'} = $loggedinuser if $mine;
301 # ($openadds) or $arghash->{approved} = 1;
302 if ($arg = $query->param('tag')) {
303 $arghash->{term} = $arg;
304 } elsif ($arg = $query->param('biblionumber')) {
305 $arghash->{biblionumber} = $arg;
307 $results = get_approval_rows($arghash);
308 my @filtered_results;
309 foreach my $my_tag (@$my_tags) {
310 if (grep { $_->{term} eq $my_tag->{term} } @$results) {
311 if (! $my_tag->{visible} ) {
312 my $check_biblio = GetMarcBiblio({
313 biblionumber => $my_tag->{biblionumber},
314 embed_items => 1,
315 opac => 1,
316 borcat => $borcat });
317 if ($check_biblio) {
318 push @filtered_results, $my_tag;
320 } else {
321 push @filtered_results, $my_tag;
325 $results = \@filtered_results;
326 stratify_tags(10, $results); # work out the differents sizes for things
327 my $count = scalar @$results;
328 $template->param(TAGLOOP_COUNT => $count, mine => $mine);
330 (scalar @errors ) and $template->param(ERRORS => \@errors);
331 my @orderedresult = sort { uc($a->{'term'}) cmp uc($b->{'term'}) } @$results;
332 (scalar @$results) and $template->param(TAGLOOP => \@orderedresult );
333 (scalar @$my_tags) and $template->param(MY_TAGS => $my_tags);
335 output_html_with_http_headers $query, $cookie, $template->output;
336 __END__
338 =head1 EXAMPLE AJAX POST PARAMETERS
340 CGISESSID 7c6288263107beb320f70f78fd767f56
341 newtag396 fire,+<a+href="foobar.html">foobar</a>,+<img+src="foo.jpg"+/>
343 So this request is trying to add 3 tags to biblio #396. The CGISESSID is the same as that the browser would
344 typically communicate using cookies. If it is valid, the server will split the value of "newtag396" and
345 process the components for addition. In this case the intended tags are:
346 fire
347 <a+href="foobar.html">foobar</a>
348 <img src="foo.jpg" />
350 The first tag is acceptable. The second will be scrubbed of markup, resulting in the tag "foobar".
351 The third tag is all markup, and will be rejected.
353 =head1 EXAMPLE AJAX JSON response
355 response = {
356 added: 2,
357 deleted: 0,
358 errors: 2,
359 alerts: [
360 KOHA.Tags.tag_message.scrubbed("foobar"),
361 KOHA.Tags.tag_message.scrubbed_all_bad("1"),
365 =cut