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