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>.
27 TODO :: Description here
29 C4::Scrubber is used to remove all markup content from the sumitted text.
36 use CGI::Cookie; # need to check cookies before having CGI parse the POST request
37 use Array::Utils qw( array_minus );
39 use C4::Auth qw( check_cookie_auth get_template_and_user );
41 use C4::Output qw( output_with_http_headers is_ajax output_html_with_http_headers );
50 use C4::XSLT qw( XSLTParse4Display );
56 use Koha::CirculationRules;
62 my $perBibResults = {};
64 # Indexes of @errors that do not apply to a particular biblionumber.
65 my @globalErrorIndexes = ();
67 sub ajax_auth_cgi { # returns CGI object
68 my $needed_flags = shift;
69 my %cookies = CGI::Cookie->fetch;
71 my $sessid = $cookies{'CGISESSID'}->value;
72 my ($auth_status) = check_cookie_auth($sessid, $needed_flags);
73 if ($auth_status ne "ok") {
74 output_with_http_headers $input, undef,
75 "window.alert('Your CGI session cookie ($sessid) is not current. " .
76 "Please refresh the page and try again.');\n", 'js';
82 # The trick here is to support multiple tags added to multiple biblios in one POST.
83 # The HTML might not use this, but it makes it more web-servicey from the start.
84 # So the name of param has to have biblionumber built in.
85 # For lack of anything more compelling, we just use "newtag[biblionumber]"
86 # We split the value into tags at comma and semicolon
88 my $is_ajax = is_ajax();
89 my $openadds = C4::Context->preference('TagsModeration') ? 0 : 1;
90 my $query = ($is_ajax) ? &ajax_auth_cgi({}) : CGI->new();
91 foreach ($query->param) {
93 my $biblionumber = $1;
94 unless ($biblionumber =~ /^\d+$/) {
95 push @errors, {+'badparam' => $_ };
96 push @globalErrorIndexes, $#errors;
99 $newtags{$biblionumber} = $query->param($_);
100 } elsif (/^del(\d+)$/) {
105 my $add_op = (scalar(keys %newtags) + scalar(@deltags)) ? 1 : 0;
106 my ($template, $loggedinuser, $cookie);
108 $loggedinuser = C4::Context->userenv->{'number'}; # must occur AFTER auth
110 ($template, $loggedinuser, $cookie) = get_template_and_user({
111 template_name => "opac-tags.tt",
114 authnotrequired => ($add_op ? 0 : 1), # auth required to add tags
118 unless ( C4::Context->preference('TagsEnabled') ) {
119 print $query->redirect("/cgi-bin/koha/errors/404.pl");
124 unless ($loggedinuser) {
125 push @errors, {+'cud-login' => 1 };
126 push @globalErrorIndexes, $#errors;
127 %newtags=(); # zero out any attempted additions
128 @deltags=(); # zero out any attempted deletions
132 my $op = $query->param('op') || q{};
134 if ( $op eq 'cud-add' ) {
136 my @newtags_keys = (keys %newtags);
137 if (scalar @newtags_keys) {
138 $scrubber = C4::Scrubber->new();
139 foreach my $biblionumber (@newtags_keys) {
140 my $bibResults = {adds=>0, errors=>[]};
141 my @values = split /[;,]/, $newtags{$biblionumber};
144 my $clean_tag = $scrubber->scrub($_);
145 unless ($clean_tag eq $_) {
146 if ($clean_tag =~ /\S/) {
147 push @errors, {scrubbed=>$clean_tag};
148 push @{$bibResults->{errors}}, {scrubbed=>$clean_tag};
150 push @errors, {scrubbed_all_bad=>1};
151 push @{$bibResults->{errors}}, {scrubbed_all_bad=>1};
152 next; # we don't add it if there's nothing left!
155 my $result = ($openadds) ?
156 add_tag($biblionumber,$clean_tag,$loggedinuser,$loggedinuser) : # pre-approved
157 add_tag($biblionumber,$clean_tag,$loggedinuser) ;
159 $counts{$biblionumber}++;
160 $bibResults->{adds}++;
162 push @errors, {failed_add_tag=>$clean_tag};
163 push @{$bibResults->{errors}}, {failed_add_tag=>$clean_tag};
164 Koha::Logger->get->warn("add_tag($biblionumber,$clean_tag,$loggedinuser...) returned bad result (" . (defined $result ? $result : 'UNDEF') .")");
167 $perBibResults->{$biblionumber} = $bibResults;
170 } elsif ( $op eq 'cud-del' ) {
172 if (remove_tag($_,$loggedinuser)) {
175 push @errors, {failed_delete=>$_};
182 foreach (values %counts) {$sum += $_;}
183 my $js_reply = sprintf("response = {\n\tadded: %d,\n\tdeleted: %d,\n\terrors: %d",$sum,$dels,scalar @errors);
185 # If no add attempts were made, flag global errors.
186 if (@globalErrorIndexes) {
187 $js_reply .= ",\n\tglobal_errors: [";
189 foreach (@globalErrorIndexes) {
190 $js_reply .= "," unless $first;
192 $js_reply .= "\n\t\t$_";
194 $js_reply .= "\n\t]";
198 if (scalar @errors) {
199 $err_string = ",\n\talerts: ["; # open response_function
202 my $key = (keys %$_)[0];
203 $err_string .= "\n\t\t KOHA.Tags.tag_message.$key(\"" . $_->{$key} . '")';
204 if($i < scalar @errors){ $err_string .= ","; }
207 $err_string .= "\n\t]\n"; # close response_function
210 # Add per-biblionumber results for use on results page
212 for my $bib (keys %$perBibResults) {
213 my $bibResult = $perBibResults->{$bib};
214 my $js_bibres = ",\n\t$bib: {\n\t\tadded: $bibResult->{adds}";
215 $js_bibres .= ",\n\t\terrors: [";
217 foreach (@{$bibResult->{errors}}) {
218 $js_bibres .= "," if ($i);
219 my $key = (keys %$_)[0];
220 $js_bibres .= "\n\t\t\t KOHA.Tags.tag_message.$key(\"" . $_->{$key} . '")';
223 $js_bibres .= "\n\t\t]\n\t}";
224 $js_perbib .= $js_bibres;
227 output_with_http_headers($query, undef, "$js_reply\n$err_string\n$js_perbib\n};", 'js');
235 my $patron = Koha::Patrons->find( { borrowernumber => $loggedinuser } );
236 my $rules = C4::Context->yaml_preference('OpacHiddenItems');
237 my $should_hide = ( $rules ) ? 1 : 0;
238 $my_tags = get_tag_rows({borrowernumber=>$loggedinuser});
239 my $my_approved_tags = get_approval_rows({ approved => 1 });
242 if( C4::Context->preference('ArticleRequests') ) {
243 $art_req_itypes = Koha::CirculationRules->guess_article_requestable_itemtypes({ $patron ? ( categorycode => $patron->categorycode ) : () });
246 # get biblionumbers stored in the cart
249 if($query->cookie("bib_list")){
250 my $cart_list = $query->cookie("bib_list");
251 @cart_list = split(/\//, $cart_list);
254 foreach my $tag (@$my_tags) {
256 my $biblio = Koha::Biblios->find( $tag->{biblionumber} );
257 my $record = $biblio->metadata->record(
267 my $items = $biblio->items->search_ordered;
268 my @all_itemnumbers = $items->get_column('itemnumber');
269 my @items_to_show = $items->filter_by_visible_in_opac({ opac => 1, patron => $patron })->as_list;
270 @hidden_items = array_minus( @all_itemnumbers, @items_to_show );
276 or ( $patron and !$patron->category->override_hidden_items )
278 and $biblio->hidden_in_opac( { rules => $rules } )
280 $tag->{title} = $biblio->title;
281 $tag->{subtitle} = $biblio->subtitle;
282 $tag->{medium} = $biblio->medium;
283 $tag->{part_number} = $biblio->part_number;
284 $tag->{part_name} = $biblio->part_name;
285 $tag->{author} = $biblio->author;
286 # BZ17530: 'Intelligent' guess if result can be article requested
287 $tag->{artreqpossible} = ( $art_req_itypes->{ $tag->{itemtype} // q{} } || $art_req_itypes->{ '*' } ) ? 1 : q{};
290 anonymous_session => ($loggedinuser) ? 0 : 1
292 $tag->{XSLTBloc} = XSLTParse4Display(
294 biblionumber => $tag->{biblionumber},
296 xsl_syspref => 'OPACXSLTResultsDisplay',
298 hidden_items => \@hidden_items,
299 xslt_variables => $variables,
303 my $date = $tag->{date_created} || '';
304 $date =~ /\s+(\d{2}\:\d{2}\:\d{2})/;
305 $tag->{time_created_display} = $1;
306 $tag->{approved} = ( grep { $_->{term} eq $tag->{term} and $_->{approved} } @$my_approved_tags );
308 # while we're checking each line, see if item is in the cart
309 if ( grep {$_ eq $biblio->biblionumber} @cart_list) {
315 $template->param(tagsview => 1);
319 for (values %counts) {$adds += $_;}
322 added_count => $adds,
323 deleted_count => $dels,
326 my ($arg,$limit,$mine);
327 my $hardmax = 100; # you might disagree what this value should be, but there definitely should be a max
328 $limit = $query->param('limit') || $hardmax;
329 $mine = $query->param('mine') || 0; # set if the patron want to see only his own tags.
330 ($limit =~ /^\d+$/ and $limit <= $hardmax) or $limit = $hardmax;
331 $template->param(limit => $limit);
332 my $arghash = {approved=>1, limit=>$limit, 'sort'=>'-weight_total'};
333 $arghash->{'borrowernumber'} = $loggedinuser if $mine;
334 # ($openadds) or $arghash->{approved} = 1;
335 if ( $arg = $query->param('tag') ) {
336 $arghash->{term} = $arg;
338 # Bug 36785: Do not pass biblionumber: get_approval_rows does not 'recognize' biblionumber
339 $results = get_approval_rows($arghash);
340 stratify_tags(10, $results); # work out the differents sizes for things
341 my $count = scalar @$results;
342 $template->param(TAGLOOP_COUNT => $count, mine => $mine);
344 (scalar @errors ) and $template->param(ERRORS => \@errors);
345 my @orderedresult = sort { uc($a->{'term'}) cmp uc($b->{'term'}) } @$results;
346 (scalar @$results) and $template->param(TAGLOOP => \@orderedresult );
347 (scalar @$my_tags) and $template->param(MY_TAGS => $my_tags);
349 output_html_with_http_headers $query, $cookie, $template->output;
352 =head1 EXAMPLE AJAX POST PARAMETERS
354 CGISESSID 7c6288263107beb320f70f78fd767f56
355 newtag396 fire,+<a+href="foobar.html">foobar</a>,+<img+src="foo.jpg"+/>
357 So this request is trying to add 3 tags to biblio #396. The CGISESSID is the same as that the browser would
358 typically communicate using cookies. If it is valid, the server will split the value of "newtag396" and
359 process the components for addition. In this case the intended tags are:
361 <a+href="foobar.html">foobar</a>
362 <img src="foo.jpg" />
364 The first tag is acceptable. The second will be scrubbed of markup, resulting in the tag "foobar".
365 The third tag is all markup, and will be rejected.
367 =head1 EXAMPLE AJAX JSON response
374 KOHA.Tags.tag_message.scrubbed("foobar"),
375 KOHA.Tags.tag_message.scrubbed_all_bad("1"),