200e8dfc47438609e51165d4cbc9505cf0c89691
[srvgit] / 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
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.
11 #
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.
16 #
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>.
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 Modern::Perl;
34
35 use CGI qw ( -utf8 );
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::Output qw(:html :ajax );
41 use C4::Scrubber;
42 use C4::Biblio;
43 use C4::Items qw(GetItemsInfo GetHiddenItemnumbers);
44 use C4::Tags qw(add_tag get_approval_rows get_tag_rows remove_tag stratify_tags);
45 use C4::XSLT;
46
47 use Data::Dumper;
48
49 use Koha::Logger;
50 use Koha::Biblios;
51 use Koha::CirculationRules;
52
53 my %newtags = ();
54 my @deltags = ();
55 my %counts  = ();
56 my @errors  = ();
57 my $perBibResults = {};
58
59 # Indexes of @errors that do not apply to a particular biblionumber.
60 my @globalErrorIndexes = ();
61
62 sub ajax_auth_cgi {     # returns CGI object
63         my $needed_flags = shift;
64     my %cookies = CGI::Cookie->fetch;
65         my $input = CGI->new;
66     my $sessid = $cookies{'CGISESSID'}->value;
67         my ($auth_status, $auth_sessid) = check_cookie_auth($sessid, $needed_flags);
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;
73         }
74         return $input;
75 }
76
77 # The trick here is to support multiple tags added to multiple bilbios in one POST.
78 # The HTML might not use this, but it makes it more web-servicey from the start.
79 # So the name of param has to have biblionumber built in.
80 # For lack of anything more compelling, we just use "newtag[biblionumber]"
81 # We split the value into tags at comma and semicolon
82
83 my $is_ajax = is_ajax();
84 my $openadds = C4::Context->preference('TagsModeration') ? 0 : 1;
85 my $query = ($is_ajax) ? &ajax_auth_cgi({}) : CGI->new();
86 foreach ($query->param) {
87     if (/^newtag(.*)/) {
88         my $biblionumber = $1;
89         unless ($biblionumber =~ /^\d+$/) {
90             push @errors, {+'badparam' => $_ };
91             push @globalErrorIndexes, $#errors;
92             next;
93         }
94         $newtags{$biblionumber} = $query->param($_);
95     } elsif (/^del(\d+)$/) {
96         push @deltags, $1;
97     }
98 }
99
100 my $add_op = (scalar(keys %newtags) + scalar(@deltags)) ? 1 : 0;
101 my ($template, $loggedinuser, $cookie);
102 if ($is_ajax) {
103         $loggedinuser = C4::Context->userenv->{'number'};  # must occur AFTER auth
104 } else {
105         ($template, $loggedinuser, $cookie) = get_template_and_user({
106         template_name   => "opac-tags.tt",
107         query           => $query,
108         type            => "opac",
109         authnotrequired => ($add_op ? 0 : 1), # auth required to add tags
110         });
111 }
112
113 unless ( C4::Context->preference('TagsEnabled') ) {
114     print $query->redirect("/cgi-bin/koha/errors/404.pl");
115     exit;
116 }
117
118 if ($add_op) {
119         unless ($loggedinuser) {
120                 push @errors, {+'login' => 1 };
121         push @globalErrorIndexes, $#errors;
122                 %newtags=();    # zero out any attempted additions
123                 @deltags=();    # zero out any attempted deletions
124         }
125 }
126
127 my $scrubber;
128 my @newtags_keys = (keys %newtags);
129 if (scalar @newtags_keys) {
130         $scrubber = C4::Scrubber->new();
131         foreach my $biblionumber (@newtags_keys) {
132         my $bibResults = {adds=>0, errors=>[]};
133                 my @values = split /[;,]/, $newtags{$biblionumber};
134                 foreach (@values) {
135                         s/^\s*(.+)\s*$/$1/;
136                         my $clean_tag = $scrubber->scrub($_);
137                         unless ($clean_tag eq $_) {
138                                 if ($clean_tag =~ /\S/) {
139                                         push @errors, {scrubbed=>$clean_tag};
140                                         push @{$bibResults->{errors}}, {scrubbed=>$clean_tag};
141                                 } else {
142                                         push @errors, {scrubbed_all_bad=>1};
143                                         push @{$bibResults->{errors}}, {scrubbed_all_bad=>1};
144                                         next;   # we don't add it if there's nothing left!
145                                 }
146                         }
147                         my $result = ($openadds) ?
148                                 add_tag($biblionumber,$clean_tag,$loggedinuser,$loggedinuser) : # pre-approved
149                                 add_tag($biblionumber,$clean_tag,$loggedinuser)   ;
150                         if ($result) {
151                                 $counts{$biblionumber}++;
152                 $bibResults->{adds}++;
153                         } else {
154                                 push @errors, {failed_add_tag=>$clean_tag};
155                                 push @{$bibResults->{errors}}, {failed_add_tag=>$clean_tag};
156                 Koha::Logger->get->warn("add_tag($biblionumber,$clean_tag,$loggedinuser...) returned bad result (" . (defined $result ? $result : 'UNDEF') .")");
157                         }
158                 }
159         $perBibResults->{$biblionumber} = $bibResults;
160         }
161 }
162 my $dels = 0;
163 foreach (@deltags) {
164         if (remove_tag($_,$loggedinuser)) {
165                 $dels++;
166         } else {
167                 push @errors, {failed_delete=>$_};
168         }
169 }
170
171 if ($is_ajax) {
172         my $sum = 0;
173         foreach (values %counts) {$sum += $_;}
174         my $js_reply = sprintf("response = {\n\tadded: %d,\n\tdeleted: %d,\n\terrors: %d",$sum,$dels,scalar @errors);
175
176     # If no add attempts were made, flag global errors.
177     if (@globalErrorIndexes) {
178         $js_reply .= ",\n\tglobal_errors: [";
179         my $first = 1;
180         foreach (@globalErrorIndexes) {
181             $js_reply .= "," unless $first;
182             $first = 0;
183             $js_reply .= "\n\t\t$_";
184         }
185         $js_reply .= "\n\t]";
186     }
187     
188         my $err_string = '';
189         if (scalar @errors) {
190                 $err_string = ",\n\talerts: ["; # open response_function
191                 my $i = 1;
192                 foreach (@errors) {
193                         my $key = (keys %$_)[0];
194                         $err_string .= "\n\t\t KOHA.Tags.tag_message.$key(\"" . $_->{$key} . '")';
195                         if($i < scalar @errors){ $err_string .= ","; }
196                         $i++;
197                 }
198                 $err_string .= "\n\t]\n";       # close response_function
199         }
200
201     # Add per-biblionumber results for use on results page
202     my $js_perbib = "";
203     for my $bib (keys %$perBibResults) {
204         my $bibResult = $perBibResults->{$bib};
205         my $js_bibres = ",\n\t$bib: {\n\t\tadded: $bibResult->{adds}";
206         $js_bibres .= ",\n\t\terrors: [";
207         my $i = 0;
208         foreach (@{$bibResult->{errors}}) {
209             $js_bibres .= "," if ($i);
210                         my $key = (keys %$_)[0];
211                         $js_bibres .= "\n\t\t\t KOHA.Tags.tag_message.$key(\"" . $_->{$key} . '")';
212             $i++;
213         }
214         $js_bibres .= "\n\t\t]\n\t}";
215         $js_perbib .= $js_bibres;
216     }
217
218         output_with_http_headers($query, undef, "$js_reply\n$err_string\n$js_perbib\n};", 'js');
219         exit;
220 }
221
222 my $results = [];
223 my $my_tags = [];
224 my $borcat  = q{};
225
226 if ($loggedinuser) {
227     my $patron = Koha::Patrons->find( { borrowernumber => $loggedinuser } );
228     $borcat = $patron ? $patron->categorycode : $borcat;
229     my $rules = C4::Context->yaml_preference('OpacHiddenItems');
230     my $should_hide = ( $rules ) ? 1 : 0;
231     $my_tags = get_tag_rows({borrowernumber=>$loggedinuser});
232     my $my_approved_tags = get_approval_rows({ approved => 1 });
233
234     my $art_req_itypes;
235     if( C4::Context->preference('ArticleRequests') ) {
236         $art_req_itypes = Koha::CirculationRules->guess_article_requestable_itemtypes({ $patron ? ( categorycode => $patron->categorycode ) : () });
237     }
238
239     # get biblionumbers stored in the cart
240     my @cart_list;
241
242     if($query->cookie("bib_list")){
243         my $cart_list = $query->cookie("bib_list");
244         @cart_list = split(/\//, $cart_list);
245     }
246
247     foreach my $tag (@$my_tags) {
248         $tag->{visible} = 0;
249         my $biblio = Koha::Biblios->find( $tag->{biblionumber} );
250         my $record = &GetMarcBiblio({
251             biblionumber => $tag->{biblionumber},
252             embed_items  => 1,
253             opac         => 1,
254             borcat       => $borcat });
255         next unless $record;
256         my $hidden_items = undef;
257         my @hidden_itemnumbers;
258         my @all_items;
259         if ($should_hide) {
260             @all_items = GetItemsInfo( $tag->{biblionumber} );
261             @hidden_itemnumbers = GetHiddenItemnumbers({
262                 items => \@all_items,
263                 borcat => $borcat });
264             $hidden_items = \@hidden_itemnumbers;
265         }
266         next
267           if (
268             (
269                 !$patron
270                 or ( $patron and !$patron->category->override_hidden_items )
271             )
272             and $biblio->hidden_in_opac( { rules => $rules } )
273           );
274         $tag->{title} = $biblio->title;
275         $tag->{subtitle} = $biblio->subtitle;
276         $tag->{medium} = $biblio->medium;
277         $tag->{part_number} = $biblio->part_number;
278         $tag->{part_name} = $biblio->part_name;
279         $tag->{author} = $biblio->author;
280         # BZ17530: 'Intelligent' guess if result can be article requested
281         $tag->{artreqpossible} = ( $art_req_itypes->{ $tag->{itemtype} // q{} } || $art_req_itypes->{ '*' } ) ? 1 : q{};
282
283         my $xslfile = C4::Context->preference('OPACXSLTResultsDisplay');
284         my $lang   = $xslfile ? C4::Languages::getlanguage()  : undef;
285         my $sysxml = $xslfile ? C4::XSLT::get_xslt_sysprefs() : undef;
286
287         if ($xslfile) {
288             my $variables = {
289                 anonymous_session => ($loggedinuser) ? 0 : 1
290             };
291             $tag->{XSLTBloc} = XSLTParse4Display(
292                 $tag->{biblionumber},     $record,
293                 "OPACXSLTResultsDisplay", 1,
294                 $hidden_items,            $sysxml,
295                 $xslfile,                 $lang,
296                 $variables
297             );
298         }
299
300         my $date = $tag->{date_created} || '';
301         $date =~ /\s+(\d{2}\:\d{2}\:\d{2})/;
302         $tag->{time_created_display} = $1;
303         $tag->{approved} = ( grep { $_->{term} eq $tag->{term} and $_->{approved} } @$my_approved_tags );
304         $tag->{visible} = 1;
305         # while we're checking each line, see if item is in the cart
306         if ( grep {$_ eq $biblio->biblionumber} @cart_list) {
307             $tag->{incart} = 1;
308         }
309     }
310 }
311
312 $template->param(tagsview => 1);
313
314 if ($add_op) {
315         my $adds = 0;
316         for (values %counts) {$adds += $_;}
317         $template->param(
318                 add_op => 1,
319                 added_count => $adds,
320                 deleted_count => $dels,
321         );
322 } else {
323         my ($arg,$limit,$mine);
324         my $hardmax = 100;      # you might disagree what this value should be, but there definitely should be a max
325         $limit = $query->param('limit') || $hardmax;
326     $mine =  $query->param('mine') || 0; # set if the patron want to see only his own tags.
327         ($limit =~ /^\d+$/ and $limit <= $hardmax) or $limit = $hardmax;
328         $template->param(limit => $limit);
329         my $arghash = {approved=>1, limit=>$limit, 'sort'=>'-weight_total'};
330     $arghash->{'borrowernumber'} = $loggedinuser if $mine;
331         # ($openadds) or $arghash->{approved} = 1;
332         if ($arg = $query->param('tag')) {
333                 $arghash->{term} = $arg;
334         } elsif ($arg = $query->param('biblionumber')) {
335                 $arghash->{biblionumber} = $arg;
336         }
337         $results = get_approval_rows($arghash);
338     stratify_tags(10, $results); # work out the differents sizes for things
339         my $count = scalar @$results;
340         $template->param(TAGLOOP_COUNT => $count, mine => $mine);
341 }
342 (scalar @errors  ) and $template->param(ERRORS  => \@errors);
343 my @orderedresult = sort { uc($a->{'term'}) cmp uc($b->{'term'}) } @$results;
344 (scalar @$results) and $template->param(TAGLOOP => \@orderedresult );
345 (scalar @$my_tags) and $template->param(MY_TAGS => $my_tags);
346
347 output_html_with_http_headers $query, $cookie, $template->output;
348 __END__
349
350 =head1 EXAMPLE AJAX POST PARAMETERS
351
352 CGISESSID       7c6288263107beb320f70f78fd767f56
353 newtag396       fire,+<a+href="foobar.html">foobar</a>,+<img+src="foo.jpg"+/>
354
355 So this request is trying to add 3 tags to biblio #396.  The CGISESSID is the same as that the browser would
356 typically communicate using cookies.  If it is valid, the server will split the value of "newtag396" and 
357 process the components for addition.  In this case the intended tags are:
358         fire
359         <a+href="foobar.html">foobar</a>
360         <img src="foo.jpg" />
361
362 The first tag is acceptable.  The second will be scrubbed of markup, resulting in the tag "foobar".  
363 The third tag is all markup, and will be rejected.  
364
365 =head1 EXAMPLE AJAX JSON response
366
367 response = {
368         added: 2,
369         deleted: 0,
370         errors: 2,
371         alerts: [
372                  KOHA.Tags.tag_message.scrubbed("foobar"),
373                  KOHA.Tags.tag_message.scrubbed_all_bad("1"),
374         ],
375 };
376
377 =cut
378