Patch security hole in vestigial report.
[koha.git] / reports / bor_issues_top.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 under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA  02111-1307 USA
19
20 use strict;
21 use CGI;
22 use C4::Auth;
23 use C4::Output;
24 use C4::Context;
25 use C4::Branch; # GetBranches
26 use C4::Koha;
27 use C4::Circulation;
28 use C4::Members;
29 use C4::Debug;
30 use C4::Dates qw(format_date format_date_in_iso);
31
32 =head1 NAME
33
34 plugin that shows a stats on borrowers
35
36 =head1 DESCRIPTION
37
38 =over 2
39
40 =cut
41
42 $debug = 1;
43 $debug and open DEBUG, ">/tmp/bor_issues_top.debug.log";
44
45 my $input = new CGI;
46 my $fullreportname = "reports/bor_issues_top.tmpl";
47 my $do_it   = $input->param('do_it');
48 my $limit   = $input->param("Limit");
49 my $column  = $input->param("Criteria");
50 my @filters = $input->param("Filter");
51 foreach ( @filters[0..3] ) {
52         $_ and $_ = format_date_in_iso($_);     
53 }
54 my $output   = $input->param("output");
55 my $basename = $input->param("basename");
56 # my $mime     = $input->param("MIME");
57 my $del      = $input->param("sep");
58 my ($template, $borrowernumber, $cookie)
59     = get_template_and_user({template_name => $fullreportname,
60                 query => $input,
61                 type => "intranet",
62                 authnotrequired => 0,
63                 flagsrequired => {reports => 1},
64                 debug => 1,
65                 });
66 $template->param(do_it => $do_it,
67         DHTMLcalendar_dateformat => C4::Dates->DHTMLcalendar(),
68         );
69 if ($do_it) {
70 # Displaying results
71     my $results = calculate($limit, $column, \@filters);
72     if ($output eq "screen"){
73 # Printing results to screen
74         $template->param(mainloop => $results, limit=>$limit);
75         output_html_with_http_headers $input, $cookie, $template->output;
76     } else {
77 # Printing to a csv file
78         print $input->header(-type => 'application/vnd.sun.xml.calc',
79                             -encoding    => 'utf-8',
80                             -attachment=>"$basename.csv",
81                             -filename=>"$basename.csv" );
82         my $cols  = @$results[0]->{loopcol};
83         my $lines = @$results[0]->{looprow};
84         my $sep;
85         $sep =C4::Context->preference("delimiter");
86 # header top-right
87         print @$results[0]->{line} ."/". @$results[0]->{column} .$sep;
88 # Other header
89                 print join($sep, map {$_->{coltitle}} @$cols);
90         print $sep . "Total\n";
91 # Table
92         foreach my $line ( @$lines ) {
93             my $x = $line->{loopcell};
94             print $line->{rowtitle}.$sep;
95                         print join($sep, map {$_->{value}} @$x);
96             print $sep,$line->{totalrow};
97             print "\n";
98         }
99 # footer
100         print "TOTAL";
101         $cols = @$results[0]->{loopfooter};
102                 print join($sep, map {$_->{totalcol}} @$cols);
103         print $sep.@$results[0]->{total};
104     }
105     exit(1);
106 }
107
108 my $dbh = C4::Context->dbh;
109 my @values;
110
111 # here each element returned by map is a hashref, get it?
112 my @mime  = ( map { +{type =>$_} } (split /[;:]/,C4::Context->preference("MIME")) );
113 my @delim = ( map { +{delim=>$_} } (split //,C4::Context->preference("delimiter")) );
114 my $branches = GetBranches;
115 my @branchloop;
116 foreach (sort keys %$branches) {
117 #       my $selected = 1 if $thisbranch eq $branch;
118         my %row = ( value => $_,
119 #                               selected => $selected,
120                                 branchname => $branches->{$_}->{branchname},
121                         );
122         push @branchloop, \%row;
123 }
124
125 my $itemtypes = GetItemTypes;
126 my @itemtypeloop;
127 foreach (sort {$itemtypes->{$a}->{description} cmp $itemtypes->{$b}->{description}} keys %$itemtypes) {
128         my %row = (value => $_,
129                description => $itemtypes->{$_}->{description},
130               );
131     push @itemtypeloop, \%row;
132 }
133     
134 my ($codes,$labels) = GetborCatFromCatType(undef,undef);
135 my @borcatloop;
136 foreach (sort keys %$labels) {
137         my %row =(value => $_,
138               description => $labels->{$_},
139              );
140     push @borcatloop, \%row;
141 }
142     
143 $template->param(
144             mimeloop => \@mime,
145              seploop => \@delim,
146           branchloop => \@branchloop,
147         itemtypeloop => \@itemtypeloop,
148           borcatloop => \@borcatloop,
149 );
150 output_html_with_http_headers $input, $cookie, $template->output;
151
152
153 sub calculate {
154     my ($line, $column, $filters) = @_;
155     my @loopcol;
156     my @loopline;
157     my @looprow;
158     my %globalline;
159         my %columns;
160     my $grantotal =0;
161     my $dbh = C4::Context->dbh;
162
163 # Checking filters
164     my @loopfilter;
165         my @cellmap = (
166                 "Issue From",
167                 "Issue To",
168                 "Return From",
169                 "Return To",
170                 "Branch",
171                 "Doc Type",
172                 "Bor Cat",
173                 "Day",
174                 "Month",
175                 "Year"
176         );
177     for (my $i=0;$i<=6;$i++) {
178         my %cell;
179         if ( @$filters[$i] ) {
180             if (($i==1) and (@$filters[$i-1])) {
181                 $cell{err} = 1 if (@$filters[$i]<@$filters[$i-1]) ;
182             }
183             # format the dates filters, otherwise just fill as is
184             $cell{filter} .= ($i>=4) ? @$filters[$i] : format_date(@$filters[$i]);
185                         defined ($cellmap[$i]) and
186                                 $cell{crit} .= $cellmap[$i];
187             push @loopfilter, \%cell;
188         }
189     }
190     my $colfield;
191     my $colorder;
192     if ($column){
193         $column = "old_issues." .$column if (($column=~/branchcode/) or ($column=~/timestamp/));
194         $column = "biblioitems.".$column if $column=~/itemtype/;
195         $column = "borrowers."  .$column if $column=~/categorycode/;
196         my @colfilter ;
197                 if ($column =~ /timestamp/) {
198                 $colfilter[0] = @$filters[0];
199                 $colfilter[1] = @$filters[1];
200                 } elsif ($column =~ /returndate/) {
201                 $colfilter[0] = @$filters[2];
202                 $colfilter[1] = @$filters[3];
203                 } elsif ($column =~ /branchcode/) {
204                         $colfilter[0] = @$filters[4];
205                 } elsif ($column =~ /itemtype/) {
206                         $colfilter[0] = @$filters[5];
207                 } elsif ($column =~ /category/) {
208                         $colfilter[0] = @$filters[6];
209                 } elsif ($column =~ /sort2/   ) {
210                         # $colfilter[0] = @$filters[11];
211                 }
212         # $colfilter[0] = @$filters[7] if ($column =~ /timestamp/ ) ; FIXME This can't be right.
213         # $colfilter[0] = @$filters[8] if ($column =~ /timestamp/ ) ; FIXME 
214         # $colfilter[0] = @$filters[9] if ($column =~ /timestamp/ ) ; FIXME Only this line would have effect.
215
216     #warn "filtre col ".$colfilter[0]." ".$colfilter[1];
217                                                 
218     # loop cols.
219         if ($column eq "Day") {
220             #Display by day
221             $column = "old_issues.timestamp";
222             $colfield .="dayname($column)";  
223             $colorder .="weekday($column)";
224         } elsif ($column eq "Month") {
225             #Display by Month
226             $column = "old_issues.timestamp";
227             $colfield .="monthname($column)";  
228             $colorder .="month($column)";  
229         } elsif ($column eq "Year") {
230             #Display by Year
231             $column = "old_issues.timestamp";
232             $colfield .="Year($column)";
233             $colorder .= $column;
234         } else {
235             $colfield .= $column;
236             $colorder .= $column;
237         }  
238
239         my $strsth2;
240         $strsth2 .= "SELECT DISTINCTROW $colfield 
241                      FROM `old_issues` 
242                      LEFT JOIN borrowers   ON old_issues.borrowernumber=borrowers.borrowernumber 
243                      LEFT JOIN items       ON old_issues.itemnumber=items.itemnumber 
244                      LEFT JOIN biblioitems ON (biblioitems.biblioitemnumber=items.biblioitemnumber)
245                      WHERE 1";
246         if (($column=~/timestamp/) or ($column=~/returndate/)){
247             if ($colfilter[1] and $colfilter[0]){
248                 $strsth2 .= " AND $column between '$colfilter[0]' AND '$colfilter[1]' " ;
249             } elsif ($colfilter[1]) {
250                 $strsth2 .= " AND $column < '$colfilter[1]' " ;
251             } elsif ($colfilter[0]) {
252                 $strsth2 .= " AND $column > '$colfilter[0]' " ;
253             }
254         } elsif ($colfilter[0]) {
255             $colfilter[0] =~ s/\*/%/g;
256             $strsth2 .= " AND $column LIKE '$colfilter[0]' " ;
257         }
258         $strsth2 .=" GROUP BY $colfield";
259         $strsth2 .=" ORDER BY $colorder";
260
261         $debug and print DEBUG "bor_issues_top (old_issues) SQL: $strsth2\n";
262         my $sth2 = $dbh->prepare($strsth2);
263         $sth2->execute;
264         print DEBUG "rows: ", $sth2->rows, "\n";
265         while (my @row = $sth2->fetchrow) {
266                         $columns{($row[0] ||'NULL')}++;
267             push @loopcol, +{ coltitle => $row[0] || 'NULL' };
268         }
269
270                 $strsth2 =~ s/old_issues/issues/g;
271         $debug and print DEBUG "bor_issues_top (issues) SQL: $strsth2\n";
272                 $sth2 = $dbh->prepare($strsth2);
273         $sth2->execute;
274         $debug and print DEBUG "rows: ", $sth2->rows, "\n";
275         while (my @row = $sth2->fetchrow) {
276                         $columns{($row[0] ||'NULL')}++;
277             push @loopcol, +{ coltitle => $row[0] || 'NULL' };
278         }
279                 $debug and print DEBUG "full array: ", Dumper(\%columns), "\n";
280     }
281
282     #Initialization of cell values.....
283     my @table;
284     for (my $i=1;$i<=$line;$i++) {
285         foreach (keys %columns) {
286 #                       warn " init table : $row->{rowtitle} / $_ ";
287             $table[$i]->{ $_ || "total" }->{'name'}=0;
288         }
289     }
290
291     my $strcalc ;
292
293 # Processing average loanperiods
294     $strcalc .= "SELECT  CONCAT(borrowers.surname , \",\\t\",borrowers.firstname),  COUNT(*) AS RANK, borrowers.borrowernumber AS ID";
295     $strcalc .= " , $colfield " if ($colfield);
296     $strcalc .= " FROM `old_issues`
297                   LEFT JOIN  borrowers  ON old_issues.borrowernumber=borrowers.borrowernumber
298                   LEFT JOIN    items    ON items.itemnumber=old_issues.itemnumber
299                   LEFT JOIN biblioitems ON (biblioitems.biblioitemnumber=items.biblioitemnumber)
300                   WHERE 1";
301         my @filterterms = (
302                 'old_issues.timestamp  >',
303                 'old_issues.timestamp  <',
304                 'old_issues.returndate >',
305                 'old_issues.returndate <',
306                 'old_issues.branchcode  like',
307                 'biblioitems.itemtype   like',
308                 'borrowers.categorycode like',
309                 'dayname(old_issues.timestamp) like',
310                 'monthname(old_issues.timestamp) like',
311                 'monthname(old_issues.timestamp) like',
312                 'year(old_issues.timestamp) like',
313         );
314     foreach ((@$filters)[0..9]) {
315                 my $term = shift @filterterms;  # go through both arrays in step
316                 ($_) or next;
317                 s/\*/%/g;
318                 $strcalc .= " AND $term '$_' ";
319         }
320     
321     $strcalc .= " GROUP BY borrowers.borrowernumber";
322     $strcalc .= ", $colfield" if ($column);
323     $strcalc .= " ORDER BY RANK DESC";
324     $strcalc .= ",$colfield " if ($colfield);
325 #       my $max;
326 #       if (@loopcol) {
327 #               $max = $line*@loopcol;
328 #       } else { $max=$line;}
329 #       $strcalc .= " LIMIT 0,$max";
330
331     $debug and print DEBUG "(old_issues) SQL : $strcalc\n";
332     my $dbcalc = $dbh->prepare($strcalc);
333     $dbcalc->execute;
334     $debug and print DEBUG "rows: ", $dbcalc->rows, "\n";
335         my %patrons = ();
336         # DATA STRUCTURE is going to look like this:
337         #       (2253=> {name=>"John Doe",
338         #                               allcols=>{MAIN=>12, MEDIA_LIB=>3}
339         #                       },
340         #       )
341     while (my @data = $dbcalc->fetchrow) {
342         my ($row, $rank, $id, $col) = @data;
343         $col = "zzEMPTY" if (!defined($col));
344                 unless ($patrons{$id}) {
345                         $patrons{$id} = {name=>$row, allcols=>{}, newcols=>{}, oldcols=>{}};
346                 }
347                 $patrons{$id}->{oldcols}->{$col} = $rank;
348     }
349
350         use Data::Dumper;
351
352         $strcalc =~ s/old_issues/issues/g;
353     $debug and print DEBUG "(issues) SQL : $strcalc\n";
354     $dbcalc = $dbh->prepare($strcalc);
355     $dbcalc->execute;
356     $debug and print DEBUG "rows: ", $dbcalc->rows, "\n";
357     while (my @data = $dbcalc->fetchrow) {
358         my ($row, $rank, $id, $col) = @data;
359         $col = "zzEMPTY" if (!defined($col));
360                 unless ($patrons{$id}) {
361                         $patrons{$id} = {name=>$row, allcols=>{}, newcols=>{}, oldcols=>{}};
362                 }
363                 $patrons{$id}->{newcols}->{$col} = $rank;
364     }
365
366         foreach my $id (keys %patrons) {
367                 my @uniq = keys %{{ %{$patrons{$id}->{newcols}}, %{$patrons{$id}->{oldcols}} }};                # get uniq keys, see perlfaq4
368                 foreach (@uniq) {
369                         my $count = ($patrons{$id}->{newcols}->{$_} || 0) +
370                                                 ($patrons{$id}->{oldcols}->{$_} || 0);
371                         $patrons{$id}->{allcols}->{$_} = $count;
372                         $patrons{$id}->{total} += $count;
373                 }
374         }
375     $debug and print DEBUG "\n\npatrons: ", Dumper(\%patrons);
376     
377         my $i = 1;
378         my @cols_in_order = sort keys %columns;         # if you want to order the columns, do something here
379         my @ranked_ids = sort {
380                                                    $patrons{$b}->{total} <=> $patrons{$a}->{total}
381                                                 || $patrons{$a}->{name}  cmp $patrons{$b}->{name}
382                                                 } keys %patrons;
383     foreach my $id (@ranked_ids) {
384         my @loopcell;
385         foreach my $key (@cols_in_order) {
386             push @loopcell, {
387                                 value => $patrons{$id}->{name},
388                                 count => $patrons{$id}->{allcols}->{$key},
389                                 reference => $id,
390                         };
391         }
392         push @looprow,{ 'rowtitle' => $i++ ,
393                         'loopcell' => \@loopcell,
394                         'hilighted' => ($i%2),
395                     };
396     }
397         
398     # the header of the table
399     $globalline{loopfilter}=\@loopfilter;
400     # the core of the table
401     $globalline{looprow} = \@looprow;
402     $globalline{loopcol} = [ map {+{coltitle=>$_}} @cols_in_order ];
403         # the foot (totals by borrower type)
404     $globalline{loopfooter} = [];
405     $globalline{total}= $grantotal;             # FIXME: useless
406     $globalline{line} = $line;
407     $globalline{column} = $column;
408     return [\%globalline];      # reference to a 1 element array: that element is a hashref
409 }
410
411 $debug and close DEBUG;
412 1;
413 __END__