Bug 17600: Standardize our EXPORT_OK
[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
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( check_cookie_auth get_template_and_user );
39 use C4::Context;
40 use C4::Output qw( output_with_http_headers is_ajax output_html_with_http_headers );
41 use C4::Scrubber;
42 use C4::Biblio qw( GetMarcBiblio );
43 use C4::Items qw( GetHiddenItemnumbers GetItemsInfo );
44 use C4::Tags qw(
45     add_tag
46     get_approval_rows
47     get_tag_rows
48     remove_tag
49     stratify_tags
50 );
51 use C4::XSLT;
52
53
54 use Koha::Logger;
55 use Koha::Biblios;
56 use Koha::CirculationRules;
57
58 my %newtags = ();
59 my @deltags = ();
60 my %counts  = ();
61 my @errors  = ();
62 my $perBibResults = {};
63
64 # Indexes of @errors that do not apply to a particular biblionumber.
65 my @globalErrorIndexes = ();
66
67 sub ajax_auth_cgi {     # returns CGI object
68         my $needed_flags = shift;
69     my %cookies = CGI::Cookie->fetch;
70         my $input = CGI->new;
71     my $sessid = $cookies{'CGISESSID'}->value;
72         my ($auth_status, $auth_sessid) = 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';
77                 exit 0;
78         }
79         return $input;
80 }
81
82 # The trick here is to support multiple tags added to multiple bilbios 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
87
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) {
92     if (/^newtag(.*)/) {
93         my $biblionumber = $1;
94         unless ($biblionumber =~ /^\d+$/) {
95             push @errors, {+'badparam' => $_ };
96             push @globalErrorIndexes, $#errors;
97             next;
98         }
99         $newtags{$biblionumber} = $query->param($_);
100     } elsif (/^del(\d+)$/) {
101         push @deltags, $1;
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 } else {
110         ($template, $loggedinuser, $cookie) = get_template_and_user({
111         template_name   => "opac-tags.tt",
112         query           => $query,
113         type            => "opac",
114         authnotrequired => ($add_op ? 0 : 1), # auth required to add tags
115         });
116 }
117
118 unless ( C4::Context->preference('TagsEnabled') ) {
119     print $query->redirect("/cgi-bin/koha/errors/404.pl");
120     exit;
121 }
122
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
129         }
130 }
131
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!
150                                 }
151                         }
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                 Koha::Logger->get->warn("add_tag($biblionumber,$clean_tag,$loggedinuser...) returned bad result (" . (defined $result ? $result : 'UNDEF') .")");
162                         }
163                 }
164         $perBibResults->{$biblionumber} = $bibResults;
165         }
166 }
167 my $dels = 0;
168 foreach (@deltags) {
169         if (remove_tag($_,$loggedinuser)) {
170                 $dels++;
171         } else {
172                 push @errors, {failed_delete=>$_};
173         }
174 }
175
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);
180
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$_";
189         }
190         $js_reply .= "\n\t]";
191     }
192     
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++;
202                 }
203                 $err_string .= "\n\t]\n";       # close response_function
204         }
205
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++;
218         }
219         $js_bibres .= "\n\t\t]\n\t}";
220         $js_perbib .= $js_bibres;
221     }
222
223         output_with_http_headers($query, undef, "$js_reply\n$err_string\n$js_perbib\n};", 'js');
224         exit;
225 }
226
227 my $results = [];
228 my $my_tags = [];
229 my $borcat  = q{};
230
231 if ($loggedinuser) {
232     my $patron = Koha::Patrons->find( { borrowernumber => $loggedinuser } );
233     $borcat = $patron ? $patron->categorycode : $borcat;
234     my $rules = C4::Context->yaml_preference('OpacHiddenItems');
235     my $should_hide = ( $rules ) ? 1 : 0;
236     $my_tags = get_tag_rows({borrowernumber=>$loggedinuser});
237     my $my_approved_tags = get_approval_rows({ approved => 1 });
238
239     my $art_req_itypes;
240     if( C4::Context->preference('ArticleRequests') ) {
241         $art_req_itypes = Koha::CirculationRules->guess_article_requestable_itemtypes({ $patron ? ( categorycode => $patron->categorycode ) : () });
242     }
243
244     # get biblionumbers stored in the cart
245     my @cart_list;
246
247     if($query->cookie("bib_list")){
248         my $cart_list = $query->cookie("bib_list");
249         @cart_list = split(/\//, $cart_list);
250     }
251
252     foreach my $tag (@$my_tags) {
253         $tag->{visible} = 0;
254         my $biblio = Koha::Biblios->find( $tag->{biblionumber} );
255         my $record = &GetMarcBiblio({
256             biblionumber => $tag->{biblionumber},
257             embed_items  => 1,
258             opac         => 1,
259             borcat       => $borcat });
260         next unless $record;
261         my $hidden_items = undef;
262         my @hidden_itemnumbers;
263         my @all_items;
264         if ($should_hide) {
265             @all_items = GetItemsInfo( $tag->{biblionumber} );
266             @hidden_itemnumbers = GetHiddenItemnumbers({
267                 items => \@all_items,
268                 borcat => $borcat });
269             $hidden_items = \@hidden_itemnumbers;
270         }
271         next
272           if (
273             (
274                 !$patron
275                 or ( $patron and !$patron->category->override_hidden_items )
276             )
277             and $biblio->hidden_in_opac( { rules => $rules } )
278           );
279         $tag->{title} = $biblio->title;
280         $tag->{subtitle} = $biblio->subtitle;
281         $tag->{medium} = $biblio->medium;
282         $tag->{part_number} = $biblio->part_number;
283         $tag->{part_name} = $biblio->part_name;
284         $tag->{author} = $biblio->author;
285         # BZ17530: 'Intelligent' guess if result can be article requested
286         $tag->{artreqpossible} = ( $art_req_itypes->{ $tag->{itemtype} // q{} } || $art_req_itypes->{ '*' } ) ? 1 : q{};
287
288         my $xslfile = C4::Context->preference('OPACXSLTResultsDisplay');
289         my $lang   = $xslfile ? C4::Languages::getlanguage()  : undef;
290         my $sysxml = $xslfile ? C4::XSLT::get_xslt_sysprefs() : undef;
291
292         if ($xslfile) {
293             my $variables = {
294                 anonymous_session => ($loggedinuser) ? 0 : 1
295             };
296             $tag->{XSLTBloc} = XSLTParse4Display(
297                 $tag->{biblionumber},     $record,
298                 "OPACXSLTResultsDisplay", 1,
299                 $hidden_items,            $sysxml,
300                 $xslfile,                 $lang,
301                 $variables
302             );
303         }
304
305         my $date = $tag->{date_created} || '';
306         $date =~ /\s+(\d{2}\:\d{2}\:\d{2})/;
307         $tag->{time_created_display} = $1;
308         $tag->{approved} = ( grep { $_->{term} eq $tag->{term} and $_->{approved} } @$my_approved_tags );
309         $tag->{visible} = 1;
310         # while we're checking each line, see if item is in the cart
311         if ( grep {$_ eq $biblio->biblionumber} @cart_list) {
312             $tag->{incart} = 1;
313         }
314     }
315 }
316
317 $template->param(tagsview => 1);
318
319 if ($add_op) {
320         my $adds = 0;
321         for (values %counts) {$adds += $_;}
322         $template->param(
323                 add_op => 1,
324                 added_count => $adds,
325                 deleted_count => $dels,
326         );
327 } else {
328         my ($arg,$limit,$mine);
329         my $hardmax = 100;      # you might disagree what this value should be, but there definitely should be a max
330         $limit = $query->param('limit') || $hardmax;
331     $mine =  $query->param('mine') || 0; # set if the patron want to see only his own tags.
332         ($limit =~ /^\d+$/ and $limit <= $hardmax) or $limit = $hardmax;
333         $template->param(limit => $limit);
334         my $arghash = {approved=>1, limit=>$limit, 'sort'=>'-weight_total'};
335     $arghash->{'borrowernumber'} = $loggedinuser if $mine;
336         # ($openadds) or $arghash->{approved} = 1;
337         if ($arg = $query->param('tag')) {
338                 $arghash->{term} = $arg;
339         } elsif ($arg = $query->param('biblionumber')) {
340                 $arghash->{biblionumber} = $arg;
341         }
342         $results = get_approval_rows($arghash);
343     stratify_tags(10, $results); # work out the differents sizes for things
344         my $count = scalar @$results;
345         $template->param(TAGLOOP_COUNT => $count, mine => $mine);
346 }
347 (scalar @errors  ) and $template->param(ERRORS  => \@errors);
348 my @orderedresult = sort { uc($a->{'term'}) cmp uc($b->{'term'}) } @$results;
349 (scalar @$results) and $template->param(TAGLOOP => \@orderedresult );
350 (scalar @$my_tags) and $template->param(MY_TAGS => $my_tags);
351
352 output_html_with_http_headers $query, $cookie, $template->output;
353 __END__
354
355 =head1 EXAMPLE AJAX POST PARAMETERS
356
357 CGISESSID       7c6288263107beb320f70f78fd767f56
358 newtag396       fire,+<a+href="foobar.html">foobar</a>,+<img+src="foo.jpg"+/>
359
360 So this request is trying to add 3 tags to biblio #396.  The CGISESSID is the same as that the browser would
361 typically communicate using cookies.  If it is valid, the server will split the value of "newtag396" and 
362 process the components for addition.  In this case the intended tags are:
363         fire
364         <a+href="foobar.html">foobar</a>
365         <img src="foo.jpg" />
366
367 The first tag is acceptable.  The second will be scrubbed of markup, resulting in the tag "foobar".  
368 The third tag is all markup, and will be rejected.  
369
370 =head1 EXAMPLE AJAX JSON response
371
372 response = {
373         added: 2,
374         deleted: 0,
375         errors: 2,
376         alerts: [
377                  KOHA.Tags.tag_message.scrubbed("foobar"),
378                  KOHA.Tags.tag_message.scrubbed_all_bad("1"),
379         ],
380 };
381
382 =cut
383