Bug 3252: Fixes XHTML on catalog statistic form page.
[koha.git] / reports / guided_reports.pl
1 #!/usr/bin/perl
2
3 # Copyright 2007 Liblime ltd
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 warnings;  # FIXME
22 use CGI;
23 use Text::CSV;
24 use C4::Reports::Guided;
25 use C4::Auth;
26 use C4::Output;
27 use C4::Dates;
28 use C4::Debug;
29
30 =head1 NAME
31
32 guided_reports.pl
33
34 =head1 DESCRIPTION
35
36 Script to control the guided report creation
37
38 =over2
39
40 =cut
41
42 my $input = new CGI;
43
44 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
45     {
46         template_name   => "reports/guided_reports_start.tmpl",
47         query           => $input,
48         type            => "intranet",
49         authnotrequired => 0,
50         flagsrequired   => { reports => 1 },
51         debug           => 1,
52     }
53 );
54
55     my @errors = ();
56 my $phase = $input->param('phase');
57 if ( !$phase ) {
58     $template->param( 'start' => 1 );
59     # show welcome page
60 }
61 elsif ( $phase eq 'Build new' ) {
62     # build a new report
63     $template->param( 'build1' => 1 );
64     $template->param( 'areas' => get_report_areas() );
65 }
66 elsif ( $phase eq 'Use saved' ) {
67     # use a saved report
68     # get list of reports and display them
69     $template->param( 'saved1' => 1 );
70     $template->param( 'savedreports' => get_saved_reports() ); 
71 }
72
73 elsif ( $phase eq 'Delete Saved') {
74         
75         # delete a report from the saved reports list
76         my $id = $input->param('reports');
77         delete_report($id);
78     print $input->redirect("/cgi-bin/koha/reports/guided_reports.pl?phase=Use%20saved");
79         exit;
80 }               
81
82 elsif ( $phase eq 'Show SQL'){
83         
84         my $id = $input->param('reports');
85         my $sql = get_sql($id);
86         $template->param(
87                 'sql' => $sql,
88                 'showsql' => 1,
89     );
90 }
91
92 elsif ( $phase eq 'Edit SQL'){
93         
94     my $id = $input->param('reports');
95     my ($sql,$type,$reportname,$notes) = get_saved_report($id);
96     $template->param(
97             'sql'        => $sql,
98             'reportname' => $reportname,
99             'id'         => $id,
100             'editsql'    => 1,
101     );
102 }
103
104 elsif ( $phase eq 'Update SQL'){
105     my $id         = $input->param('id');
106     my $sql        = $input->param('sql');
107     my $reportname = $input->param('reportname');
108     my @errors;
109     if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
110         push @errors, {sqlerr => $1};
111     }
112     elsif ($sql !~ /^(SELECT)/i) {
113         push @errors, {queryerr => 1};
114     }
115     if (@errors) {
116         $template->param(
117             'errors'    => \@errors,
118             'sql'       => $sql,
119         );
120     }
121     else {
122         update_sql( $id, $sql, $reportname );
123         $template->param(
124             'save_successful'       => 1,
125         );
126     }
127     
128 }
129
130 elsif ($phase eq 'retrieve results') {
131         my $id = $input->param('id');
132         my ($results,$name,$notes) = format_results($id);
133         # do something
134         $template->param(
135                 'retresults' => 1,
136                 'results' => $results,
137                 'name' => $name,
138                 'notes' => $notes,
139     );
140 }
141
142 elsif ( $phase eq 'Report on this Area' ) {
143
144     # they have choosen a new report and the area to report on
145     $template->param(
146         'build2' => 1,
147         'area'   => $input->param('areas'),
148         'types'  => get_report_types(),
149     );
150 }
151
152 elsif ( $phase eq 'Choose this type' ) {
153
154     # they have chosen type and area
155     # get area and type and pass them to the template
156     my $area = $input->param('area');
157     my $type = $input->param('types');
158     $template->param(
159         'build3' => 1,
160         'area'   => $area,
161         'type'   => $type,
162         columns  => get_columns($area,$input),
163     );
164 }
165
166 elsif ( $phase eq 'Choose these columns' ) {
167
168     # we now know type, area, and columns
169     # next step is the constraints
170     my $area    = $input->param('area');
171     my $type    = $input->param('type');
172     my @columns = $input->param('columns');
173     my $column  = join( ',', @columns );
174     $template->param(
175         'build4' => 1,
176         'area'   => $area,
177         'type'   => $type,
178         'column' => $column,
179         definitions => get_from_dictionary($area),
180         criteria    => get_criteria($area,$input),
181     );
182 }
183
184 elsif ( $phase eq 'Choose these criteria' ) {
185     my $area     = $input->param('area');
186     my $type     = $input->param('type');
187     my $column   = $input->param('column');
188         my @definitions = $input->param('definition');
189         my $definition = join (',',@definitions);
190     my @criteria = $input->param('criteria_column');
191         my $query_criteria;
192     foreach my $crit (@criteria) {
193         my $value = $input->param( $crit . "_value" );
194         ($value) or next;
195         if ($value =~ C4::Dates->regexp('syspref')) { 
196             $value = C4::Dates->new($value)->output("iso");
197         }
198         $query_criteria .= " AND $crit='$value'";
199     }
200
201     $template->param(
202         'build5'         => 1,
203         'area'           => $area,
204         'type'           => $type,
205         'column'         => $column,
206         'definition'     => $definition,
207         'criteriastring' => $query_criteria,
208     );
209
210     # get columns
211     my @columns = split( ',', $column );
212     my @total_by;
213
214     # build structue for use by tmpl_loop to choose columns to order by
215     # need to do something about the order of the order :)
216         # we also want to use the %columns hash to get the plain english names
217     foreach my $col (@columns) {
218         my %total = (name => $col);
219         my @selects = map {+{ value => $_ }} (qw(sum min max avg count));
220         $total{'select'} = \@selects;
221         push @total_by, \%total;
222     }
223
224     $template->param( 'total_by' => \@total_by );
225 }
226
227 elsif ( $phase eq 'Choose These Operations' ) {
228     my $area     = $input->param('area');
229     my $type     = $input->param('type');
230     my $column   = $input->param('column');
231     my $criteria = $input->param('criteria');
232         my $definition = $input->param('definition');
233     my @total_by = $input->param('total_by');
234     my $totals;
235     foreach my $total (@total_by) {
236         my $value = $input->param( $total . "_tvalue" );
237         $totals .= "$value($total),";
238     }
239
240     $template->param(
241         'build6'         => 1,
242         'area'           => $area,
243         'type'           => $type,
244         'column'         => $column,
245         'criteriastring' => $criteria,
246         'totals'         => $totals,
247         'definition'     => $definition,
248     );
249
250     # get columns
251     my @columns = split( ',', $column );
252     my @order_by;
253
254     # build structue for use by tmpl_loop to choose columns to order by
255     # need to do something about the order of the order :)
256     foreach my $col (@columns) {
257         my %order = (name => $col);
258         my @selects = map {+{ value => $_ }} (qw(asc desc));
259         $order{'select'} = \@selects;
260         push @order_by, \%order;
261     }
262
263     $template->param( 'order_by' => \@order_by );
264 }
265
266 elsif ( $phase eq 'Build Report' ) {
267
268     # now we have all the info we need and can build the sql
269     my $area     = $input->param('area');
270     my $type     = $input->param('type');
271     my $column   = $input->param('column');
272     my $crit     = $input->param('criteria');
273     my $totals   = $input->param('totals');
274         my $definition = $input->param('definition');
275 #    my @criteria = split( ',', $crit );
276     my $query_criteria=$crit;
277     # split the columns up by ,
278     my @columns = split( ',', $column );
279     my @order_by = $input->param('order_by');
280
281     my $query_orderby;
282     foreach my $order (@order_by) {
283         my $value = $input->param( $order . "_ovalue" );
284         if ($query_orderby) {
285             $query_orderby .= ",$order $value";
286         }
287         else {
288             $query_orderby = " ORDER BY $order $value";
289         }
290     }
291
292     # get the sql
293     my $sql =
294       build_query( \@columns, $query_criteria, $query_orderby, $area, $totals, $definition );
295     $template->param(
296         'showreport' => 1,
297         'sql'        => $sql,
298         'type'       => $type
299     );
300 }
301
302 elsif ( $phase eq 'Save' ) {
303         # Save the report that has just been built
304     my $sql  = $input->param('sql');
305     my $type = $input->param('type');
306     $template->param(
307         'save' => 1,
308         'sql'  => $sql,
309         'type' => $type
310     );
311 }
312
313 elsif ( $phase eq 'Save Report' ) {
314     # save the sql pasted in by a user 
315     my $sql  = $input->param('sql');
316     my $name = $input->param('reportname');
317     my $type = $input->param('types');
318     my $notes = $input->param('notes');
319     if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
320         push @errors, {sqlerr => $1};
321     }
322     elsif ($sql !~ /^(SELECT)/i) {
323         push @errors, {queryerr => 1};
324     }
325     if (@errors) {
326         $template->param(
327             'errors'    => \@errors,
328             'sql'       => $sql,
329             'reportname'=> $name,
330             'type'      => $type,
331             'notes'     => $notes,
332         );
333     }
334     else {
335         save_report( $borrowernumber, $sql, $name, $type, $notes );
336         $template->param(
337             'save_successful'       => 1,
338         );
339     }
340 }
341
342 elsif ($phase eq 'Run this report'){
343     # execute a saved report
344     my $limit  = 20;    # page size. # TODO: move to DB or syspref?
345     my $offset = 0;
346     my $report = $input->param('reports');
347     # offset algorithm
348     if ($input->param('page')) {
349         $offset = ($input->param('page') - 1) * $limit;
350     }
351     my ($sql,$type,$name,$notes) = get_saved_report($report);
352     unless ($sql) {
353         push @errors, {no_sql_for_id=>$report};   
354     } 
355     my @rows = ();
356     my ($sth, $errors) = execute_query($sql, $offset, $limit);
357     my $total = select_2_select_count_value($sql) || 0;
358     unless ($sth) {
359         die "execute_query failed to return sth for report $report: $sql";
360     } else {
361         my $headref = $sth->{NAME} || [];
362         my @headers = map { +{ cell => $_ } } @$headref;
363         $template->param(header_row => \@headers);
364         while (my $row = $sth->fetchrow_arrayref()) {
365             my @cells = map { +{ cell => $_ } } @$row;
366             push @rows, { cells => \@cells };
367         }
368     }
369
370     my $totpages = int($total/$limit) + (($total % $limit) > 0 ? 1 : 0);
371     my $url = "/cgi-bin/koha/reports/guided_reports.pl?reports=$report&phase=Run%20this%20report";
372     $template->param(
373         'results' => \@rows,
374         'sql'     => $sql,
375         'execute' => 1,
376         'name'    => $name,
377         'notes'   => $notes,
378         'errors'  => $errors,
379         'pagination_bar'  => pagination_bar($url, $totpages, $input->param('page')),
380         'unlimited_total' => $total,
381     );
382 }       
383
384 elsif ($phase eq 'Export'){
385     binmode STDOUT, ':utf8';
386
387         # export results to tab separated text or CSV
388         my $sql    = $input->param('sql');  # FIXME: use sql from saved report ID#, not new user-supplied SQL!
389     my $format = $input->param('format');
390         my ($sth, $q_errors) = execute_query($sql);
391     unless ($q_errors and @$q_errors) {
392         print $input->header(       -type => 'application/octet-stream',
393                                     -attachment=>"reportresults.$format"
394                             );
395         if ($format eq 'tab') {
396             print join("\t", header_cell_values($sth)), "\n";
397             while (my $row = $sth->fetchrow_arrayref()) {
398                 print join("\t", @$row), "\n";
399             }
400         } else {
401             my $csv = Text::CSV->new({binary => 1});
402             $csv or die "Text::CSV->new({binary => 1}) FAILED: " . Text::CSV->error_diag();
403             if ($csv->combine(header_cell_values($sth))) {
404                 print $csv->string(), "\n";
405             } else {
406                 push @$q_errors, { combine => 'HEADER ROW: ' . $csv->error_diag() } ;
407             }
408             while (my $row = $sth->fetchrow_arrayref()) {
409                 if ($csv->combine(@$row)) {
410                     print $csv->string(), "\n"; 
411                 } else {
412                     push @$q_errors, { combine => $csv->error_diag() } ;
413                 }
414             }
415         }
416         foreach my $err (@$q_errors, @errors) {
417             print "# ERROR: " . (map {$_ . ": " . $err->{$_}} keys %$err) . "\n";
418         }   # here we print all the non-fatal errors at the end.  Not super smooth, but better than nothing.
419         exit;
420     }
421     $template->param(
422         'sql'           => $sql,
423         'execute'       => 1,
424         'name'          => 'Error exporting report!',
425         'notes'         => '',
426         'errors'        => $q_errors,
427     );
428 }
429
430 elsif ($phase eq 'Create report from SQL') {
431         # allow the user to paste in sql
432     if ($input->param('sql')) {
433         $template->param(
434             'sql'           => $input->param('sql'),
435             'reportname'    => $input->param('reportname'),
436             'notes'         => $input->param('notes'),
437         );
438     }
439         $template->param('create' => 1);
440 }
441
442 elsif ($phase eq 'Create Compound Report'){
443         $template->param( 'savedreports' => get_saved_reports(),
444                 'compound' => 1,
445         );
446 }
447
448 elsif ($phase eq 'Save Compound'){
449     my $master    = $input->param('master');
450         my $subreport = $input->param('subreport');
451         my ($mastertables,$subtables) = create_compound($master,$subreport);
452         $template->param( 'save_compound' => 1,
453                 master=>$mastertables,
454                 subsql=>$subtables
455         );
456 }
457
458 # pass $sth, get back an array of names for the column headers
459 sub header_cell_values {
460     my $sth = shift or return ();
461     return @{$sth->{NAME}};
462 }
463
464 # pass $sth, get back a TMPL_LOOP-able set of names for the column headers
465 sub header_cell_loop {
466     my @headers = map { +{ cell => $_ } } header_cell_values (shift);
467     return \@headers;
468 }
469
470 foreach (1..6) {
471     $template->param('build' . $_) and $template->param(buildx => $_) and last;
472 }
473 $template->param(   'referer' => $input->referer(),
474                     'DHTMLcalendar_dateformat' => C4::Dates->DHTMLcalendar(),
475                 );
476
477 output_html_with_http_headers $input, $cookie, $template->output;