Bug 25898: Prohibit indirect object notation
[koha.git] / reports / borrowers_stats.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 use Modern::Perl;
21 use CGI qw ( -utf8 );
22 use List::MoreUtils qw/uniq/;
23
24 use C4::Auth;
25 use C4::Context;
26 use C4::Koha;
27 use C4::Acquisition;
28 use C4::Output;
29 use C4::Reports;
30 use C4::Circulation;
31
32 use Koha::AuthorisedValues;
33 use Koha::DateUtils;
34 use Koha::Libraries;
35 use Koha::Patron::Attribute::Types;
36 use Koha::Patron::Categories;
37
38 use Date::Calc qw(
39   Today
40   Add_Delta_YM
41   );
42
43 =head1 NAME
44
45 plugin that shows a stats on borrowers
46
47 =head1 DESCRIPTION
48
49 =cut
50
51 my $input = CGI->new;
52 my $do_it=$input->param('do_it');
53 my $fullreportname = "reports/borrowers_stats.tt";
54 my $line = $input->param("Line");
55 my $column = $input->param("Column");
56 my @filters = $input->multi_param("Filter");
57 $filters[3] = eval { output_pref( { dt => dt_from_string( $filters[3]), dateonly => 1, dateformat => 'iso' } ); }
58     if ( $filters[3] );
59 $filters[4] = eval { output_pref ({ dt => dt_from_string( $filters[4]), dateonly => 1, dateformat => 'iso' } ); }
60     if ( $filters[4] );
61 my $digits = $input->param("digits");
62 our $period = $input->param("period");
63 my $borstat = $input->param("status");
64 my $borstat1 = $input->param("activity");
65 my $output = $input->param("output");
66 my $basename = $input->param("basename");
67 our $sep     = $input->param("sep");
68 $sep = "\t" if ($sep and $sep eq 'tabulation');
69
70 my ($template, $borrowernumber, $cookie)
71         = get_template_and_user({template_name => $fullreportname,
72                                 query => $input,
73                                 type => "intranet",
74                                 flagsrequired => {reports => '*'},
75                                 debug => 1,
76                                 });
77 $template->param(do_it => $do_it);
78 if ($do_it) {
79         my $attributes;
80         if (C4::Context->preference('ExtendedPatronAttributes')) {
81             $attributes = parse_extended_patron_attributes($input);
82         }
83         my $results = calculate($line, $column, $digits, $borstat,$borstat1 ,\@filters, $attributes);
84         if ($output eq "screen"){
85                 $template->param(mainloop => $results);
86                 output_html_with_http_headers $input, $cookie, $template->output;
87         } else {
88                 print $input->header(-type => 'application/vnd.sun.xml.calc',
89                          -encoding => 'utf-8',
90                              -name => "$basename.csv",
91                        -attachment => "$basename.csv");
92                 my $cols = @$results[0]->{loopcol};
93                 my $lines = @$results[0]->{looprow};
94                 print @$results[0]->{line} ."/". @$results[0]->{column} .$sep;
95                 foreach my $col ( @$cols ) {
96                         print $col->{coltitle}.$sep;
97                 }
98                 print "Total\n";
99                 foreach my $line ( @$lines ) {
100                         my $x = $line->{loopcell};
101                         print $line->{rowtitle}.$sep;
102                         foreach my $cell (@$x) {
103                                 print $cell->{value}.$sep;
104                         }
105                         print $line->{totalrow};
106                         print "\n";
107                 }
108                 print "TOTAL";
109                 $cols = @$results[0]->{loopfooter};
110                 foreach my $col ( @$cols ) {
111                         print $sep.$col->{totalcol};
112                 }
113                 print $sep.@$results[0]->{total};
114         }
115         exit;   # exit after do_it, regardless
116 } else {
117         my $dbh = C4::Context->dbh;
118         my $req;
119     my $patron_categories = Koha::Patron::Categories->search({}, {order_by => ['description']});
120     $template->param( patron_categories => $patron_categories );
121         $req = $dbh->prepare("SELECT DISTINCTROW zipcode FROM borrowers WHERE zipcode IS NOT NULL AND zipcode <> '' ORDER BY zipcode");
122         $req->execute;
123         $template->param(   ZIP_LOOP => $req->fetchall_arrayref({}));
124         $req = $dbh->prepare("SELECT authorised_value,lib FROM authorised_values WHERE category='Bsort1' ORDER BY lib");
125         $req->execute;
126         $template->param( SORT1_LOOP => $req->fetchall_arrayref({}));
127         $req = $dbh->prepare("SELECT DISTINCTROW sort2 AS value FROM borrowers WHERE sort2 IS NOT NULL AND sort2 <> '' ORDER BY sort2 LIMIT 200");
128     # More than 200 items in a dropdown is not going to be useful anyway, and w/ 50,000 patrons we can destroy DB performance.
129         $req->execute;
130         $template->param( SORT2_LOOP => $req->fetchall_arrayref({}));
131         
132     my $CGIextChoice = ( 'CSV' ); # FIXME translation
133         my $CGIsepChoice=GetDelimiterChoices;
134         $template->param(
135                 CGIextChoice => $CGIextChoice,
136                 CGIsepChoice => $CGIsepChoice,
137     );
138     if (C4::Context->preference('ExtendedPatronAttributes')) {
139         patron_attributes_form($template);
140     }
141 }
142 output_html_with_http_headers $input, $cookie, $template->output;
143
144 sub calculate {
145         my ($line, $column, $digits, $status, $activity, $filters, $attr_filters) = @_;
146
147         my @mainloop;
148         my @loopfooter;
149         my @loopcol;
150         my @loopline;
151         my @looprow;
152         my %globalline;
153         my $grantotal =0;
154 # extract parameters
155         my $dbh = C4::Context->dbh;
156
157     # check parameters
158     my @valid_names = qw(categorycode zipcode branchcode sex sort1 sort2);
159     if ($line =~ /^patron_attr\.(.*)/) {
160         my $attribute_type = $1;
161         return unless Koha::Patron::Attribute::Types->find($attribute_type);
162     } else {
163         return unless (grep { $_ eq $line } @valid_names);
164     }
165     if ($column =~ /^patron_attr\.(.*)/) {
166         my $attribute_type = $1;
167         return unless Koha::Patron::Attribute::Types->find($attribute_type);
168     } else {
169         return unless (grep { $_ eq $column } @valid_names);
170     }
171     return if ($digits and $digits !~ /^\d+$/);
172     return if ($status and (grep { $_ eq $status } qw(debarred gonenoaddress lost)) == 0);
173     return if ($activity and (grep { $_ eq $activity } qw(active nonactive)) == 0);
174
175     # Filters
176     my $linefilter;
177     if    ( $line =~ /categorycode/ ) { $linefilter = @$filters[0]; }
178     elsif ( $line =~ /zipcode/ )      { $linefilter = @$filters[1]; }
179     elsif ( $line =~ /branchcode/ )   { $linefilter = @$filters[2]; }
180     elsif ( $line =~ /sex/ )          { $linefilter = @$filters[5]; }
181     elsif ( $line =~ /sort1/ )        { $linefilter = @$filters[6]; }
182     elsif ( $line =~ /sort2/ )        { $linefilter = @$filters[7]; }
183     elsif ( $line =~ /^patron_attr\.(.*)$/ ) { $linefilter = $attr_filters->{$1}; }
184     else  { $linefilter = ''; }
185
186     my $colfilter;
187     if    ( $column =~ /categorycode/ ) { $colfilter = @$filters[0]; }
188     elsif ( $column =~ /zipcode/ )      { $colfilter = @$filters[1]; }
189     elsif ( $column =~ /branchcode/)    { $colfilter = @$filters[2]; }
190     elsif ( $column =~ /sex/)           { $colfilter = @$filters[5]; }
191     elsif ( $column =~ /sort1/)         { $colfilter = @$filters[6]; }
192     elsif ( $column =~ /sort2/)         { $colfilter = @$filters[7]; }
193     elsif ( $column =~ /^patron_attr\.(.*)$/) { $colfilter = $attr_filters->{$1}; }
194     else  { $colfilter = ''; }
195
196     my @loopfilter;
197     foreach my $i (0 .. scalar @$filters) {
198         my %cell;
199         if ( @$filters[$i] ) {
200             if ($i == 3 or $i == 4) {
201                 $cell{filter} = eval { output_pref( { dt => dt_from_string( @$filters[$i] ), dateonly => 1 }); }
202                     if ( @$filters[$i] );
203             } else {
204                 $cell{filter} = @$filters[$i];
205             }
206
207             if    ( $i == 0)  { $cell{crit} = "Cat code"; }
208             elsif ( $i == 1 ) { $cell{crit} = "ZIP/Postal code"; }
209             elsif ( $i == 2 ) { $cell{crit} = "Branch code"; }
210             elsif ( $i == 3 ||
211                     $i == 4 ) { $cell{crit} = "Date of birth"; }
212             elsif ( $i == 5 ) { $cell{crit} = "Sex"; }
213             elsif ( $i == 6 ) { $cell{crit} = "Sort1"; }
214             elsif ( $i == 7 ) { $cell{crit} = "Sort2"; }
215             else { $cell{crit} = "Unknown"; }
216
217             push @loopfilter, \%cell;
218         }
219     }
220     foreach my $type (keys %$attr_filters) {
221         if($attr_filters->{$type}) {
222             push @loopfilter, {
223                 crit => "Attribute $type",
224                 filter => $attr_filters->{$type}
225             }
226         }
227     }
228
229     my @branchcodes = map { $_->branchcode } Koha::Libraries->search;
230         ($status  ) and push @loopfilter,{crit=>"Status",  filter=>$status  };
231         ($activity) and push @loopfilter,{crit=>"Activity",filter=>$activity};
232 # year of activity
233         my ( $period_year, $period_month, $period_day )=Add_Delta_YM( Today(),-$period, 0);
234         my $newperioddate=$period_year."-".$period_month."-".$period_day;
235 # 1st, loop rows.
236         my $linefield;
237
238     my $line_attribute_type;
239     if ($line  =~/^patron_attr\.(.*)$/) {
240         $line_attribute_type = $1;
241         $line = 'borrower_attributes.attribute';
242     }
243
244     if (($line =~/zipcode/) and ($digits)) {
245         $linefield = "left($line,$digits)";
246     } else {
247         $linefield = $line;
248     }
249     my $patron_categories = Koha::Patron::Categories->search({}, {order_by => ['categorycode']});
250
251     my $strsth;
252     my @strparams; # bind parameters for the query
253     if ($line_attribute_type) {
254         $strsth = "SELECT distinct attribute FROM borrower_attributes
255             WHERE attribute IS NOT NULL AND code=?";
256         push @strparams, $line_attribute_type;
257     } else {
258         $strsth = "SELECT distinctrow $linefield FROM borrowers
259             WHERE $line IS NOT NULL ";
260     }
261
262         $linefilter =~ s/\*/%/g;
263         if ( $linefilter ) {
264                 $strsth .= " AND $linefield LIKE ? " ;
265                 push @strparams, $linefilter;
266         }
267         $strsth .= " AND $status='1' " if ($status);
268     $strsth .=" order by $linefield";
269         
270         my $sth = $dbh->prepare($strsth);
271     $sth->execute(@strparams);
272         while (my ($celvalue) = $sth->fetchrow) {
273                 my %cell;
274                 if ($celvalue) {
275                         $cell{rowtitle} = $celvalue;
276             $cell{rowtitle_display} = ($patron_categories->find($celvalue)->description || "$celvalue\*") if ($line eq 'categorycode');
277                 }
278                 $cell{totalrow} = 0;
279                 push @loopline, \%cell;
280         }
281
282 # 2nd, loop cols.
283         my $colfield;
284
285     my $column_attribute_type;
286     if ($column  =~/^patron_attr.(.*)$/) {
287         $column_attribute_type = $1;
288         $column = 'borrower_attributes.attribute';
289     }
290
291     if (($column =~/zipcode/) and ($digits)) {
292         $colfield = "left($column,$digits)";
293     } else {
294         $colfield = $column;
295     }
296
297     my $strsth2;
298     my @strparams2; # bind parameters for the query
299     if ($column_attribute_type) {
300         $strsth2 = "SELECT DISTINCT attribute FROM borrower_attributes
301             WHERE attribute IS NOT NULL AND code=?";
302         push @strparams2, $column_attribute_type;
303     } else {
304         $strsth2 = "SELECT DISTINCTROW $colfield FROM borrowers
305             WHERE $column IS NOT NULL";
306     }
307
308         if ($colfilter) {
309                 $colfilter =~ s/\*/%/g;
310                 $strsth2 .= " AND $colfield LIKE ? ";
311         push @strparams2, $colfield;
312         }
313         $strsth2 .= " AND $status='1' " if ($status);
314
315     $strsth2 .= " order by $colfield";
316         my $sth2 = $dbh->prepare($strsth2);
317     $sth2->execute(@strparams2);
318         while (my ($celvalue) = $sth2->fetchrow) {
319                 my %cell;
320              if (defined $celvalue) {
321                         $cell{coltitle} = $celvalue;
322                         # $cell{coltitle_display} = ($colfield eq 'branchcode') ? $branches->{$celvalue}->{branchname} : $celvalue;
323             $cell{coltitle_display} = $patron_categories->find($celvalue)->description if ($column eq 'categorycode');
324                 }
325                 push @loopcol, \%cell;
326         }
327
328         my $i=0;
329         #Initialization of cell values.....
330         my %table;
331 #       warn "init table";
332         foreach my $row (@loopline) {
333                 foreach my $col ( @loopcol ) {
334             my $rowtitle = $row->{rowtitle} // '';
335             my $coltitle = $row->{coltitle} // '';
336             $table{$rowtitle}->{$coltitle} = 0;
337                 }
338         $row->{rowtitle} ||= '';
339                 $table{$row->{rowtitle}}->{totalrow}=0;
340                 $table{$row->{rowtitle}}->{rowtitle_display} = $row->{rowtitle_display};
341         }
342
343     # preparing calculation
344     my $strcalc;
345     my @calcparams;
346     $strcalc = "SELECT ";
347     if ($line_attribute_type) {
348         $strcalc .= " attribute_$line_attribute_type.attribute AS line_attribute, ";
349     } else {
350         $strcalc .= " $linefield, ";
351     }
352     if ($column_attribute_type) {
353         $strcalc .= " attribute_$column_attribute_type.attribute AS column_attribute, ";
354     } else {
355         $strcalc .= " $colfield, ";
356     }
357
358     $strcalc .= " COUNT(*) FROM borrowers ";
359     foreach my $type (keys %$attr_filters) {
360         if (
361             ($line_attribute_type and $line_attribute_type eq $type)
362          or ($column_attribute_type and $column_attribute_type eq $type)
363          or ($attr_filters->{$type})
364         ) {
365             $strcalc .= " LEFT JOIN borrower_attributes AS attribute_$type
366                 ON (borrowers.borrowernumber = attribute_$type.borrowernumber
367                     AND attribute_$type.code = " . $dbh->quote($type) . ") ";
368         }
369     }
370     $strcalc .= " WHERE 1 ";
371
372         @$filters[0]=~ s/\*/%/g if (@$filters[0]);
373         $strcalc .= " AND categorycode like '" . @$filters[0] ."'" if ( @$filters[0] );
374         @$filters[1]=~ s/\*/%/g if (@$filters[1]);
375         $strcalc .= " AND zipcode like '" . @$filters[1] ."'" if ( @$filters[1] );
376         @$filters[2]=~ s/\*/%/g if (@$filters[2]);
377         $strcalc .= " AND branchcode like '" . @$filters[2] ."'" if ( @$filters[2] );
378         @$filters[3]=~ s/\*/%/g if (@$filters[3]);
379         $strcalc .= " AND dateofbirth > '" . @$filters[3] ."'" if ( @$filters[3] );
380         @$filters[4]=~ s/\*/%/g if (@$filters[4]);
381         $strcalc .= " AND dateofbirth < '" . @$filters[4] ."'" if ( @$filters[4] );
382     @$filters[5]=~ s/\*/%/g if (@$filters[5]);
383     $strcalc .= " AND sex like '" . @$filters[5] ."'" if ( @$filters[5] );
384     @$filters[6]=~ s/\*/%/g if (@$filters[6]);
385         $strcalc .= " AND sort1 like '" . @$filters[6] ."'" if ( @$filters[6] );
386         @$filters[7]=~ s/\*/%/g if (@$filters[7]);
387         $strcalc .= " AND sort2 like '" . @$filters[7] ."'" if ( @$filters[7] );
388
389     foreach my $type (keys %$attr_filters) {
390         if($attr_filters->{$type}) {
391             my $filter = $attr_filters->{$type};
392             $filter =~ s/\*/%/g;
393             $strcalc .= " AND attribute_$type.attribute LIKE '" . $filter . "' ";
394         }
395     }
396     $strcalc .= " AND borrowers.borrowernumber in (select distinct(borrowernumber) from old_issues where issuedate > '" . $newperioddate . "')" if ($activity eq 'active');
397     $strcalc .= " AND borrowers.borrowernumber not in (select distinct(borrowernumber) from old_issues where issuedate > '" . $newperioddate . "' AND borrowernumber IS NOT NULL)" if ($activity eq 'nonactive');
398         $strcalc .= " AND $status='1' " if ($status);
399
400     $strcalc .= " GROUP BY ";
401     if ($line_attribute_type) {
402         $strcalc .= " line_attribute, ";
403     } else {
404         $strcalc .= " $linefield, ";
405     }
406     if ($column_attribute_type) {
407         $strcalc .= " column_attribute ";
408     } else {
409         $strcalc .= " $colfield ";
410     }
411
412         my $dbcalc = $dbh->prepare($strcalc);
413         (scalar(@calcparams)) ? $dbcalc->execute(@calcparams) : $dbcalc->execute();
414         
415         my $emptycol; 
416         while (my ($row, $col, $value) = $dbcalc->fetchrow) {
417 #               warn "filling table $row / $col / $value ";
418                 $emptycol = 1 if (!defined($col));
419                 $col = "zzEMPTY" if (!defined($col));
420                 $row = "zzEMPTY" if (!defined($row));
421                 
422                 $table{$row}->{$col}+=$value;
423                 $table{$row}->{totalrow}+=$value;
424                 $grantotal += $value;
425         }
426         
427         push @loopcol,{coltitle => "NULL"} if ($emptycol);
428         
429         foreach my $row (sort keys %table) {
430                 my @loopcell;
431                 #@loopcol ensures the order for columns is common with column titles
432                 # and the number matches the number of columns
433                 foreach my $col ( @loopcol ) {
434             my $coltitle = $col->{coltitle} // '';
435             $coltitle = $coltitle eq "NULL" ? "zzEMPTY" : $coltitle;
436                         my $value =$table{$row}->{$coltitle};
437                         push @loopcell, {value => $value};
438                 }
439                 push @looprow,{
440                         'rowtitle' => ($row eq "zzEMPTY")?"NULL":$row,
441                         'rowtitle_display' => $table{$row}->{rowtitle_display} || ($row eq "zzEMPTY" ? "NULL" : $row),
442                         'loopcell' => \@loopcell,
443                         'totalrow' => $table{$row}->{totalrow}
444                 };
445         }
446         
447         foreach my $col ( @loopcol ) {
448                 my $total=0;
449                 foreach my $row ( @looprow ) {
450             my $rowtitle = $row->{rowtitle} // '';
451             $rowtitle = ($rowtitle eq "NULL") ? "zzEMPTY" : $rowtitle;
452             my $coltitle = $col->{coltitle} // '';
453             $coltitle = ($coltitle eq "NULL") ? "zzEMPTY" : $coltitle;
454
455             $total += $table{$rowtitle}->{$coltitle} || 0;
456 #                       warn "value added ".$table{$row->{rowtitle}}->{$col->{coltitle}}. "for line ".$row->{rowtitle};
457                 }
458 #               warn "summ for column ".$col->{coltitle}."  = ".$total;
459                 push @loopfooter, {'totalcol' => $total};
460         }
461                         
462
463         # the header of the table
464         $globalline{loopfilter}=\@loopfilter;
465         # the core of the table
466         $globalline{looprow} = \@looprow;
467         $globalline{loopcol} = \@loopcol;
468 #       # the foot (totals by borrower type)
469         $globalline{loopfooter} = \@loopfooter;
470         $globalline{total}= $grantotal;
471         $globalline{line} = ($line_attribute_type) ? $line_attribute_type : $line;
472         $globalline{column} = ($column_attribute_type) ? $column_attribute_type : $column;
473         push @mainloop,\%globalline;
474         return \@mainloop;
475 }
476
477 sub parse_extended_patron_attributes {
478     my ($input) = @_;
479
480     my @params_names = $input->param;
481     my %attr;
482     foreach my $name (@params_names) {
483         if ($name =~ /^Filter_patron_attr\.(.*)$/) {
484             my $code = $1;
485             my $value = $input->param($name);
486             $attr{$code} = $value;
487         }
488     }
489
490     return \%attr;
491 }
492
493
494 sub patron_attributes_form {
495     my $template = shift;
496
497     my $library_id = C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef;
498     my $attribute_types = Koha::Patron::Attribute::Types->search_with_library_limits({}, {}, $library_id);
499
500     my %items_by_class;
501     while ( my $attr_type = $attribute_types->next ) {
502         # TODO The following can be simplified easily
503         my $entry = {
504             class             => $attr_type->class(),
505             code              => $attr_type->code(),
506             description       => $attr_type->description(),
507             repeatable        => $attr_type->repeatable(),
508             category          => $attr_type->authorised_value_category(),
509             category_code     => $attr_type->category_code(),
510         };
511
512         my $newentry = { %$entry };
513         if ($attr_type->authorised_value_category()) {
514             $newentry->{use_dropdown} = 1;
515             $newentry->{auth_val_loop} = GetAuthorisedValues(
516                 $attr_type->authorised_value_category()
517             );
518         }
519         push @{ $items_by_class{ $attr_type->class() } }, $newentry;
520     }
521
522     my @attribute_loop;
523     foreach my $class ( sort keys %items_by_class ) {
524         my $av = Koha::AuthorisedValues->search({ category => 'PA_CLASS', authorised_value => $class });
525         my $lib = $av->count ? $av->next->lib : $class;
526         push @attribute_loop, {
527             class => $class,
528             items => $items_by_class{$class},
529             lib   => $lib,
530         };
531     }
532
533     $template->param(patron_attributes => \@attribute_loop);
534
535 }