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