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