Initial commit for Tags back-end moderation. Requires AJAX functions from Output.
[koha.git] / tags / review.pl
1 #!/usr/bin/perl
2
3 # This software is placed under the gnu General Public License, v2 (http://www.gnu.org/licenses/gpl.html)
4
5 # Copyright 2008 LibLime
6 #
7 # This file is part of Koha.
8 #
9 # Koha is free software; you can redistribute it and/or modify it under the
10 # terms of the GNU General Public License as published by the Free Software
11 # Foundation; either version 2 of the License, or (at your option) any later
12 # version.
13 #
14 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
15 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
16 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License along with
19 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
20 # Suite 330, Boston, MA  02111-1307 USA
21
22 use warnings;
23 use strict;
24 use Data::Dumper;
25 use POSIX;
26 use CGI;
27 use CGI::Cookie; # need to check cookies before having CGI parse the POST request
28
29 use C4::Auth qw(:DEFAULT check_cookie_auth);;
30 use C4::Context;
31 use C4::Dates qw(format_date format_date_in_iso);
32 # use C4::Koha;
33 use C4::Output 3.02 qw(:html :ajax pagination_bar);
34 use C4::Debug;
35 use C4::Tags 0.02 qw(get_tags get_approval_rows whitelist blacklist is_approved);
36
37 sub counts () { 
38         my $query = "SELECT " .
39         #               (SELECT count(*) FROM tags_all     ) as tags_all,
40         #               (SELECT count(*) FROM tags_index   ) as tags_index,
41         "               (SELECT count(*) FROM tags_approval WHERE approved= 1) as approved_count,
42                         (SELECT count(*) FROM tags_approval WHERE approved=-1) as rejected_count,
43                         (SELECT count(*) FROM tags_approval WHERE approved= 0) as unapproved_count
44         ";
45         my $sth = C4::Context->dbh->prepare($query);
46         $sth->execute;
47         my $result = $sth->fetchrow_hashref();
48         $result->{approved_total} = $result->{approved_count} + $result->{rejected_count} + $result->{unapproved_count};
49         $debug and warn "counts returned: " . Dumper $result;
50         return $result;
51 }
52
53 my $script_name = "/cgi-bin/koha/tags/review.pl";
54 my $needed_flags = { tools => 'moderate_comments' };    # FIXME: replace when more specific permission is created.
55
56 sub ajax_auth_cgi ($) {         # returns CGI object
57         my $needed_flags = shift;
58         my %cookies = fetch CGI::Cookie;
59         my $input = CGI->new;
60         my $sessid = $cookies{'CGISESSID'}->value || $input->param('CGISESSID');
61         my ($auth_status, $auth_sessid) = check_cookie_auth($sessid, $needed_flags);
62         $debug and
63         print STDERR "($auth_status, $auth_sessid) = check_cookie_auth($sessid," . Dumper($needed_flags) . ")\n";
64         if ($auth_status ne "ok") {
65                 output_ajax_with_http_headers $input,
66                         "window.alert('Your CGI session cookie ($sessid) is not current.  " . 
67                         "Please refresh the page and try again.');\n";
68                 exit 0;
69         }
70         $debug and print STDERR "AJAX request: " . Dumper($input),
71                 "\n(\$auth_status,\$auth_sessid) = ($auth_status,$auth_sessid)\n";
72         return $input;
73 }
74
75 if (is_ajax()) {
76         my $input = &ajax_auth_cgi($needed_flags);
77         my $operator = C4::Context->userenv->{'number'};  # must occur AFTER auth
78         $debug and print STDERR "op: " . Dumper($operator) . "\n";
79         my ($tag, $js_reply);
80         if ($tag = $input->param('test')) {
81                 $js_reply = ( is_approved(          $tag) ? 'success' : 'failure') . "_test('$tag');\n";
82         }
83         if ($tag = $input->param('ok')) {
84                 $js_reply = (   whitelist($operator,$tag) ? 'success' : 'failure') . "_approve('$tag');\n";
85         } 
86         if ($tag = $input->param('rej')) {
87                 $js_reply = (   blacklist($operator,$tag) ? 'success' : 'failure')  . "_reject('$tag');\n";
88         }
89         output_ajax_with_http_headers $input, $js_reply;
90         exit;
91 }
92
93 ### Below is the sad, boring, necessary non-AJAX HTML code.
94
95 my $input = CGI->new;
96 my ($template, $borrowernumber, $cookie) = get_template_and_user({
97                 template_name => "tags/review.tmpl",
98                 query => $input,
99                  type => "intranet",
100                 debug => 1,
101                 authnotrequired => 0,
102                   flagsrequired => $needed_flags,
103 });
104
105 my ($op, @errors, @tags);
106 $op   = $input->param('op') || 'none';
107 @tags = $input->param('tags');
108
109 $borrowernumber == 0 and push @errors, {op_zero=>1};
110      if ($op eq 'approve') {
111         foreach (@tags) {
112                 whitelist($borrowernumber,$_) or push @errors, {failed_ok=>$_};
113         }
114 } elsif ($op eq 'reject' ) {
115         foreach (@tags) {
116                 blacklist($borrowernumber,$_) or push @errors, {failed_rej=>$_};
117         }
118 } elsif ($op eq 'test'   ) {
119         my $tag = $input->param('test');
120         push @tags, $tag;
121         $template->param(
122                 test_term => $tag,
123                 (is_approved($tag) ? 'verdict_ok' : 'verdict_rej') => 1,
124         );
125 }
126
127 my $counts = &counts;
128 foreach (keys %$counts) {
129         $template->param($_ => $counts->{$_});
130 }
131
132 sub pagination_calc ($;$) {
133         my $query = shift or return undef;      
134         my $hardlimit = (@_) ? shift : 100;     # hardcoded, could be another syspref
135         my $pagesize = $query->param('limit' ) || $hardlimit;
136         my $page     = $query->param('page'  ) || 1;
137         my $offset   = $query->param('offset') || 0;
138         ($pagesize <= $hardlimit) or $pagesize = $hardlimit;
139         if ($page > 1) {
140                 $offset = ($page-1)*$pagesize;
141         } else {
142                 $page = 1;
143         }
144         return ($pagesize,$page,$offset);
145 }
146
147 my ($pagesize,$page,$offset) = pagination_calc($input,100);
148
149 my %filters = (
150         limit => $offset ? "$offset,$pagesize" : $pagesize,
151          sort => 'approved,-weight_total,+term',
152 );
153 my ($filter,$date_from,$date_to);
154 if (defined $input->param('approved')) { # 0 is valid value, must check defined
155         $filter = $input->param('approved');
156 } else {
157         $filter = 0;
158 }
159 if ($filter eq 'all') {
160         $template->param(filter_approved_all => 1);
161 } elsif ($filter =~ /-?[01]/) {
162         $filters{approved} = $filter;
163         $template->param(
164                 ($filter == 1  ? 'filter_approved_ok'      : 
165                  $filter == 0  ? 'filter_approved_pending' :
166                  $filter == -1 ? 'filter_approved_rej'     :
167                 'filter_approved') => 1
168         );
169 }
170
171 # my $q_count = get_approval_rows({limit=>$pagesize, sort=>'approved,-weight_total,+term', count=>1});
172 if ($filter = $input->param('tag')) {
173         $template->param(filter_tag=>$filter);
174         $filters{term} = $filter;
175 }
176 if ($filter = $input->param('from')) {
177         if ($date_from = format_date_in_iso($filter)) {
178                 $template->param(filter_date_approved_from=>$filter);
179                 $filters{date_approved} = ">=$date_from";
180         } else {
181                 push @errors, {date_from=>$filter};
182         }
183 }
184 if ($filter = $input->param('to')) {
185         if ($date_to = format_date_in_iso($filter)) {
186                 $template->param(filter_date_approved_to=>$filter);
187                 $filters{date_approved} = "<=$date_to";
188         } else {
189                 push @errors, {date_to=>$filter};
190         }
191 }
192 if ($filter = $input->param('approver')) {              # name (or borrowernumber) from input box
193         if (($filter =~ /^\d+$/ and $filter > 0) or
194                 (1) ){  # $filter=get borrowernumber from name
195                 $template->param(filter_approver=>$filter);
196                 $filters{approved_by} = $filter;
197         # } else {
198                 push @errors, {approver=>$filter};
199         }
200 }
201 if ($filter = $input->param('approved_by')) {   # borrowernumber from link
202         if ($filter =~ /^\d+$/ and $filter > 0) {
203                 $template->param(filter_approver=>$filter);
204                 $filters{approved_by} = $filter;
205         } else {
206                 push @errors, {approved_by=>$filter};
207         }
208 }
209 $debug and print STDERR "filters: " . Dumper(\%filters);
210 my $tagloop = get_approval_rows(\%filters);
211 my $qstring = $input->query_string;
212 $qstring =~ s/([&;])*\blimit=\d+//;             # remove pagination vars
213 # $qstring =~ s/([&;])*\bpage=\d+//;            # remove pagination vars
214 # $qstring =~ s/\&[\&]+/&/g;            # compress duplicates
215 # $qstring =~ s/;;+/;/g;                # compress duplicates
216 # $qstring =~ s/\&;//g;         # remove empties
217 # $qstring =~ s/;+$//;          # remove trailing delim
218 $qstring =~ s/^;+//;            # remove leading delim
219 $qstring = "limit=$pagesize" . ($qstring ? '&amp;' . $qstring : '');
220 $debug and print STDERR "number of approval_rows: " . scalar(@$tagloop) . "rows\n";
221 (scalar @errors) and $template->param(message_loop=>\@errors);
222 $template->param(
223         DHTMLcalendar_dateformat => C4::Dates->DHTMLcalendar(),
224         offset => $offset,      # req'd for EXPR
225         op => $op,
226         op_count => scalar(@tags),
227         script_name => $script_name,
228         approved => 0,          # dummy value (also EXPR)
229         tagloop => $tagloop,
230         pagination_bar => pagination_bar(
231                 "$script_name?$qstring\&amp;",
232                 ceil($counts->{approved_total}/$pagesize),      # $page, 'page'
233         )
234 );
235
236 output_html_with_http_headers $input, $cookie, $template->output;
237 __END__
238