Merge remote-tracking branch 'kc/new/bug_5449' into kcmaster
[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
17 # with Koha; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19
20 use strict;
21 #use warnings; FIXME - Bug 2505
22 use CGI;
23 use Text::CSV;
24 use C4::Reports::Guided;
25 use C4::Auth qw/:DEFAULT get_session/;
26 use C4::Output;
27 use C4::Dates;
28 use C4::Debug;
29 use C4::Branch; # XXX subfield_is_koha_internal_p
30
31 =head1 NAME
32
33 guided_reports.pl
34
35 =head1 DESCRIPTION
36
37 Script to control the guided report creation
38
39 =cut
40
41 my $input = new CGI;
42
43 my $phase = $input->param('phase');
44 my $flagsrequired;
45 if ( $phase eq 'Build new' or $phase eq 'Delete Saved' ) {
46     $flagsrequired = 'create_reports';
47 }
48 elsif ( $phase eq 'Use saved' ) {
49     $flagsrequired = 'execute_reports';
50 } else {
51     $flagsrequired = '*';
52 }
53
54 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
55     {
56         template_name   => "reports/guided_reports_start.tmpl",
57         query           => $input,
58         type            => "intranet",
59         authnotrequired => 0,
60         flagsrequired   => { reports => $flagsrequired },
61         debug           => 1,
62     }
63 );
64 my $session = $cookie ? get_session($cookie->value) : undef;
65
66 my $filter;
67 if ( $input->param("filter_set") ) {
68     $filter = {};
69     $filter->{$_} = $input->param("filter_$_") foreach qw/date author keyword/;
70     $session->param('report_filter', $filter) if $session;
71 }
72 elsif ($session) {
73     $filter = $session->param('report_filter');
74 }
75
76
77 my @errors = ();
78 if ( !$phase ) {
79     $template->param( 'start' => 1 );
80     # show welcome page
81 }
82 elsif ( $phase eq 'Build new' ) {
83     # build a new report
84     $template->param( 'build1' => 1 );
85     $template->param( 'areas' => get_report_areas() );
86 }
87 elsif ( $phase eq 'Use saved' ) {
88     # use a saved report
89     # get list of reports and display them
90     $template->param(
91         'saved1' => 1,
92         'savedreports' => get_saved_reports($filter),
93     );
94     if ($filter) {
95         while ( my ($k, $v) = each %$filter ) {
96             $template->param( "filter_$k" => $v ) if $v;
97         }
98     }
99 }
100
101 elsif ( $phase eq 'Delete Saved') {
102         
103         # delete a report from the saved reports list
104         my $id = $input->param('reports');
105         delete_report($id);
106     print $input->redirect("/cgi-bin/koha/reports/guided_reports.pl?phase=Use%20saved");
107         exit;
108 }               
109
110 elsif ( $phase eq 'Show SQL'){
111         
112         my $id = $input->param('reports');
113         my $sql = get_sql($id);
114         $template->param(
115                 'sql' => $sql,
116                 'showsql' => 1,
117     );
118 }
119
120 elsif ( $phase eq 'Edit SQL'){
121         
122     my $id = $input->param('reports');
123     my ($sql,$type,$reportname,$notes) = get_saved_report($id);
124     $template->param(
125             'sql'        => $sql,
126             'reportname' => $reportname,
127         'notes'      => $notes,
128         'id'         => $id,
129             'editsql'    => 1,
130     );
131 }
132
133 elsif ( $phase eq 'Update SQL'){
134     my $id         = $input->param('id');
135     my $sql        = $input->param('sql');
136     my $reportname = $input->param('reportname');
137     my $notes      = $input->param('notes');
138     my @errors;
139     if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
140         push @errors, {sqlerr => $1};
141     }
142     elsif ($sql !~ /^(SELECT)/i) {
143         push @errors, {queryerr => 1};
144     }
145     if (@errors) {
146         $template->param(
147             'errors'    => \@errors,
148             'sql'       => $sql,
149         );
150     }
151     else {
152         update_sql( $id, $sql, $reportname, $notes );
153         $template->param(
154             'save_successful'       => 1,
155             'id'                    => $id,
156         );
157     }
158     
159 }
160
161 elsif ($phase eq 'retrieve results') {
162         my $id = $input->param('id');
163         my ($results,$name,$notes) = format_results($id);
164         # do something
165         $template->param(
166                 'retresults' => 1,
167                 'results' => $results,
168                 'name' => $name,
169                 'notes' => $notes,
170     );
171 }
172
173 elsif ( $phase eq 'Report on this Area' ) {
174
175     # they have choosen a new report and the area to report on
176     $template->param(
177         'build2' => 1,
178         'area'   => $input->param('areas'),
179         'types'  => get_report_types(),
180     );
181 }
182
183 elsif ( $phase eq 'Choose this type' ) {
184
185     # they have chosen type and area
186     # get area and type and pass them to the template
187     my $area = $input->param('area');
188     my $type = $input->param('types');
189     $template->param(
190         'build3' => 1,
191         'area'   => $area,
192         'type'   => $type,
193         columns  => get_columns($area,$input),
194     );
195 }
196
197 elsif ( $phase eq 'Choose these columns' ) {
198
199     # we now know type, area, and columns
200     # next step is the constraints
201     my $area    = $input->param('area');
202     my $type    = $input->param('type');
203     my @columns = $input->param('columns');
204     my $column  = join( ',', @columns );
205     $template->param(
206         'build4' => 1,
207         'area'   => $area,
208         'type'   => $type,
209         'column' => $column,
210         definitions => get_from_dictionary($area),
211         criteria    => get_criteria($area,$input),
212     );
213 }
214
215 elsif ( $phase eq 'Choose these criteria' ) {
216     my $area     = $input->param('area');
217     my $type     = $input->param('type');
218     my $column   = $input->param('column');
219         my @definitions = $input->param('definition');
220         my $definition = join (',',@definitions);
221     my @criteria = $input->param('criteria_column');
222         my $query_criteria;
223     foreach my $crit (@criteria) {
224         my $value = $input->param( $crit . "_value" );
225         
226         # If value is not defined, then it may be range values
227         if (!defined $value) {
228
229             my $fromvalue = $input->param( "from_" . $crit . "_value" );
230             my $tovalue   = $input->param( "to_"   . $crit . "_value" );
231             
232             # If the range values are dates
233             if ($fromvalue =~ C4::Dates->regexp('syspref') && $tovalue =~ C4::Dates->regexp('syspref')) { 
234                 $fromvalue = C4::Dates->new($fromvalue)->output("iso");
235                 $tovalue = C4::Dates->new($tovalue)->output("iso");
236             }
237
238             if ($fromvalue && $tovalue) {
239                 $query_criteria .= " AND $crit >= '$fromvalue' AND $crit <= '$tovalue'";
240             }
241
242         } else {
243
244             # If value is a date
245             if ($value =~ C4::Dates->regexp('syspref')) { 
246                 $value = C4::Dates->new($value)->output("iso");
247             }
248         # don't escape runtime parameters, they'll be at runtime
249         if ($value =~ /<<.*>>/) {
250             $query_criteria .= " AND $crit=$value";
251         } else {
252             $query_criteria .= " AND $crit='$value'";
253         }
254         }
255     }
256
257     $template->param(
258         'build5'         => 1,
259         'area'           => $area,
260         'type'           => $type,
261         'column'         => $column,
262         'definition'     => $definition,
263         'criteriastring' => $query_criteria,
264     );
265
266     # get columns
267     my @columns = split( ',', $column );
268     my @total_by;
269
270     # build structue for use by tmpl_loop to choose columns to order by
271     # need to do something about the order of the order :)
272         # we also want to use the %columns hash to get the plain english names
273     foreach my $col (@columns) {
274         my %total = (name => $col);
275         my @selects = map {+{ value => $_ }} (qw(sum min max avg count));
276         $total{'select'} = \@selects;
277         push @total_by, \%total;
278     }
279
280     $template->param( 'total_by' => \@total_by );
281 }
282
283 elsif ( $phase eq 'Choose These Operations' ) {
284     my $area     = $input->param('area');
285     my $type     = $input->param('type');
286     my $column   = $input->param('column');
287     my $criteria = $input->param('criteria');
288         my $definition = $input->param('definition');
289     my @total_by = $input->param('total_by');
290     my $totals;
291     foreach my $total (@total_by) {
292         my $value = $input->param( $total . "_tvalue" );
293         $totals .= "$value($total),";
294     }
295
296     $template->param(
297         'build6'         => 1,
298         'area'           => $area,
299         'type'           => $type,
300         'column'         => $column,
301         'criteriastring' => $criteria,
302         'totals'         => $totals,
303         'definition'     => $definition,
304     );
305
306     # get columns
307     my @columns = split( ',', $column );
308     my @order_by;
309
310     # build structue for use by tmpl_loop to choose columns to order by
311     # need to do something about the order of the order :)
312     foreach my $col (@columns) {
313         my %order = (name => $col);
314         my @selects = map {+{ value => $_ }} (qw(asc desc));
315         $order{'select'} = \@selects;
316         push @order_by, \%order;
317     }
318
319     $template->param( 'order_by' => \@order_by );
320 }
321
322 elsif ( $phase eq 'Build Report' ) {
323
324     # now we have all the info we need and can build the sql
325     my $area     = $input->param('area');
326     my $type     = $input->param('type');
327     my $column   = $input->param('column');
328     my $crit     = $input->param('criteria');
329     my $totals   = $input->param('totals');
330     my $definition = $input->param('definition');
331     my $query_criteria=$crit;
332     # split the columns up by ,
333     my @columns = split( ',', $column );
334     my @order_by = $input->param('order_by');
335
336     my $query_orderby;
337     foreach my $order (@order_by) {
338         my $value = $input->param( $order . "_ovalue" );
339         if ($query_orderby) {
340             $query_orderby .= ",$order $value";
341         }
342         else {
343             $query_orderby = " ORDER BY $order $value";
344         }
345     }
346
347     # get the sql
348     my $sql =
349       build_query( \@columns, $query_criteria, $query_orderby, $area, $totals, $definition );
350     $template->param(
351         'showreport' => 1,
352         'sql'        => $sql,
353         'type'       => $type
354     );
355 }
356
357 elsif ( $phase eq 'Save' ) {
358         # Save the report that has just been built
359     my $sql  = $input->param('sql');
360     my $type = $input->param('type');
361     $template->param(
362         'save' => 1,
363         'sql'  => $sql,
364         'type' => $type
365     );
366 }
367
368 elsif ( $phase eq 'Save Report' ) {
369     # save the sql pasted in by a user 
370     my $sql  = $input->param('sql');
371     my $name = $input->param('reportname');
372     my $type = $input->param('types');
373     my $notes = $input->param('notes');
374     if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
375         push @errors, {sqlerr => $1};
376     }
377     elsif ($sql !~ /^(SELECT)/i) {
378         push @errors, {queryerr => 1};
379     }
380     if (@errors) {
381         $template->param(
382             'errors'    => \@errors,
383             'sql'       => $sql,
384             'reportname'=> $name,
385             'type'      => $type,
386             'notes'     => $notes,
387         );
388     }
389     else {
390         my $id = save_report( $borrowernumber, $sql, $name, $type, $notes );
391         $template->param(
392             'save_successful'       => 1,
393             'id'                    => $id,
394         );
395     }
396 }
397
398 elsif ($phase eq 'Run this report'){
399     # execute a saved report
400     my $limit  = 20;    # page size. # TODO: move to DB or syspref?
401     my $offset = 0;
402     my $report = $input->param('reports');
403     my @sql_params = $input->param('sql_params');
404     # offset algorithm
405     if ($input->param('page')) {
406         $offset = ($input->param('page') - 1) * $limit;
407     }
408     my ($sql,$type,$name,$notes) = get_saved_report($report);
409     unless ($sql) {
410         push @errors, {no_sql_for_id=>$report};   
411     } 
412     my @rows = ();
413     # if we have at least 1 parameter, and it's not filled, then don't execute but ask for parameters
414     if ($sql =~ /<</ && !@sql_params) {
415         # split on ??. Each odd (2,4,6,...) entry should be a parameter to fill
416         my @split = split /<<|>>/,$sql;
417         my @tmpl_parameters;
418         for(my $i=0;$i<($#split/2);$i++) {
419             my ($text,$authorised_value) = split /\|/,$split[$i*2+1];
420             my $input;
421             if ($authorised_value) {
422                 my $dbh=C4::Context->dbh;
423                 my @authorised_values;
424                 my %authorised_lib;
425                 # builds list, depending on authorised value...
426                 if ( $authorised_value eq "branches" ) {
427                     my $branches = GetBranchesLoop();
428                     foreach my $thisbranch (@$branches) {
429                         push @authorised_values, $thisbranch->{value};
430                         $authorised_lib{$thisbranch->{value}} = $thisbranch->{branchname};
431                     }
432                 }
433                 elsif ( $authorised_value eq "itemtypes" ) {
434                     my $sth = $dbh->prepare("SELECT itemtype,description FROM itemtypes ORDER BY description");
435                     $sth->execute;
436                     while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
437                         push @authorised_values, $itemtype;
438                         $authorised_lib{$itemtype} = $description;
439                     }
440                 }
441                 elsif ( $authorised_value eq "cn_source" ) {
442                     my $class_sources = GetClassSources();
443                     my $default_source = C4::Context->preference("DefaultClassificationSource");
444                     foreach my $class_source (sort keys %$class_sources) {
445                         next unless $class_sources->{$class_source}->{'used'} or
446                                     ($class_source eq $default_source);
447                         push @authorised_values, $class_source;
448                         $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
449                     }
450                 }
451                 elsif ( $authorised_value eq "categorycode" ) {
452                     my $sth = $dbh->prepare("SELECT categorycode, description FROM categories ORDER BY description");
453                     $sth->execute;
454                     while ( my ( $categorycode, $description ) = $sth->fetchrow_array ) {
455                         push @authorised_values, $categorycode;
456                         $authorised_lib{$categorycode} = $description;
457                     }
458
459                     #---- "true" authorised value
460                 }
461                 else {
462                     my $authorised_values_sth = $dbh->prepare("SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib");
463
464                     $authorised_values_sth->execute( $authorised_value);
465
466                     while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
467                         push @authorised_values, $value;
468                         $authorised_lib{$value} = $lib;
469                         # For item location, we show the code and the libelle
470                         $authorised_lib{$value} = $lib;
471                     }
472                 }
473                 $input =CGI::scrolling_list(      # FIXME: factor out scrolling_list
474                     -name     => "sql_params",
475                     -values   => \@authorised_values,
476 #                     -default  => $value,
477                     -labels   => \%authorised_lib,
478                     -override => 1,
479                     -size     => 1,
480                     -multiple => 0,
481                     -tabindex => 1,
482                 );
483
484             } else {
485                 $input = "<input type='text' name='sql_params'/>";
486             }
487             push @tmpl_parameters, {'entry' => $text, 'input' => $input };
488         }
489         $template->param('sql'         => $sql,
490                         'name'         => $name,
491                         'sql_params'   => \@tmpl_parameters,
492                         'enter_params' => 1,
493                         'reports'      => $report,
494                         );
495     } else {
496         # OK, we have parameters, or there are none, we run the report
497         # if there were parameters, replace before running
498         # split on ??. Each odd (2,4,6,...) entry should be a parameter to fill
499         my @split = split /<<|>>/,$sql;
500         my @tmpl_parameters;
501         for(my $i=0;$i<$#split/2;$i++) {
502             my $quoted = C4::Context->dbh->quote($sql_params[$i]);
503             # if there are special regexp chars, we must \ them
504             $split[$i*2+1] =~ s/(\||\?|\.|\*|\(|\)|\%)/\\$1/g;
505             $sql =~ s/<<$split[$i*2+1]>>/$quoted/;
506         }
507         my ($sth, $errors) = execute_query($sql, $offset, $limit);
508         my $total = nb_rows($sql) || 0;
509         unless ($sth) {
510             die "execute_query failed to return sth for report $report: $sql";
511         } else {
512             my $headref = $sth->{NAME} || [];
513             my @headers = map { +{ cell => $_ } } @$headref;
514             $template->param(header_row => \@headers);
515             while (my $row = $sth->fetchrow_arrayref()) {
516                 my @cells = map { +{ cell => $_ } } @$row;
517                 push @rows, { cells => \@cells };
518             }
519         }
520
521         my $totpages = int($total/$limit) + (($total % $limit) > 0 ? 1 : 0);
522         my $url = "/cgi-bin/koha/reports/guided_reports.pl?reports=$report&amp;phase=Run%20this%20report";
523         $template->param(
524             'results' => \@rows,
525             'sql'     => $sql,
526             'execute' => 1,
527             'name'    => $name,
528             'notes'   => $notes,
529             'errors'  => $errors,
530             'pagination_bar'  => pagination_bar($url, $totpages, $input->param('page')),
531             'unlimited_total' => $total,
532         );
533     }
534 }
535
536 elsif ($phase eq 'Export'){
537     binmode STDOUT, ':utf8';
538
539         # export results to tab separated text or CSV
540         my $sql    = $input->param('sql');  # FIXME: use sql from saved report ID#, not new user-supplied SQL!
541     my $format = $input->param('format');
542         my ($sth, $q_errors) = execute_query($sql);
543     unless ($q_errors and @$q_errors) {
544         print $input->header(       -type => 'application/octet-stream',
545                                     -attachment=>"reportresults.$format"
546                             );
547         if ($format eq 'tab') {
548             print join("\t", header_cell_values($sth)), "\n";
549             while (my $row = $sth->fetchrow_arrayref()) {
550                 print join("\t", @$row), "\n";
551             }
552         } else {
553             my $csv = Text::CSV->new({binary => 1});
554             $csv or die "Text::CSV->new({binary => 1}) FAILED: " . Text::CSV->error_diag();
555             if ($csv->combine(header_cell_values($sth))) {
556                 print $csv->string(), "\n";
557             } else {
558                 push @$q_errors, { combine => 'HEADER ROW: ' . $csv->error_diag() } ;
559             }
560             while (my $row = $sth->fetchrow_arrayref()) {
561                 if ($csv->combine(@$row)) {
562                     print $csv->string(), "\n"; 
563                 } else {
564                     push @$q_errors, { combine => $csv->error_diag() } ;
565                 }
566             }
567         }
568         foreach my $err (@$q_errors, @errors) {
569             print "# ERROR: " . (map {$_ . ": " . $err->{$_}} keys %$err) . "\n";
570         }   # here we print all the non-fatal errors at the end.  Not super smooth, but better than nothing.
571         exit;
572     }
573     $template->param(
574         'sql'           => $sql,
575         'execute'       => 1,
576         'name'          => 'Error exporting report!',
577         'notes'         => '',
578         'errors'        => $q_errors,
579     );
580 }
581
582 elsif ($phase eq 'Create report from SQL') {
583         # allow the user to paste in sql
584     if ($input->param('sql')) {
585         $template->param(
586             'sql'           => $input->param('sql'),
587             'reportname'    => $input->param('reportname'),
588             'notes'         => $input->param('notes'),
589         );
590     }
591         $template->param('create' => 1);
592 }
593
594 elsif ($phase eq 'Create Compound Report'){
595         $template->param( 'savedreports' => get_saved_reports(),
596                 'compound' => 1,
597         );
598 }
599
600 elsif ($phase eq 'Save Compound'){
601     my $master    = $input->param('master');
602         my $subreport = $input->param('subreport');
603         my ($mastertables,$subtables) = create_compound($master,$subreport);
604         $template->param( 'save_compound' => 1,
605                 master=>$mastertables,
606                 subsql=>$subtables
607         );
608 }
609
610 # pass $sth, get back an array of names for the column headers
611 sub header_cell_values {
612     my $sth = shift or return ();
613     return @{$sth->{NAME}};
614 }
615
616 # pass $sth, get back a TMPL_LOOP-able set of names for the column headers
617 sub header_cell_loop {
618     my @headers = map { +{ cell => $_ } } header_cell_values (shift);
619     return \@headers;
620 }
621
622 foreach (1..6) {
623     $template->param('build' . $_) and $template->param(buildx => $_) and last;
624 }
625 $template->param(   'referer' => $input->referer(),
626                     'DHTMLcalendar_dateformat' => C4::Dates->DHTMLcalendar(),
627                 );
628
629 output_html_with_http_headers $input, $cookie, $template->output;