Bug 10379 - Followup: add koha-rebuild-zebra -q to the man 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
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
21 use CGI qw/-utf8/;
22 use Text::CSV;
23 use URI::Escape;
24 use C4::Reports::Guided;
25 use C4::Auth qw/:DEFAULT get_session/;
26 use C4::Output;
27 use C4::Dates qw/format_date/;
28 use C4::Debug;
29 use C4::Branch; # XXX subfield_is_koha_internal_p
30 use C4::Koha qw/IsAuthorisedValueCategory/;
31
32 =head1 NAME
33
34 guided_reports.pl
35
36 =head1 DESCRIPTION
37
38 Script to control the guided report creation
39
40 =cut
41
42 my $input = new CGI;
43 my $usecache = C4::Context->ismemcached;
44
45 my $phase = $input->param('phase');
46 my $flagsrequired;
47 if ( $phase eq 'Build new' or $phase eq 'Delete Saved' ) {
48     $flagsrequired = 'create_reports';
49 }
50 elsif ( $phase eq 'Use saved' ) {
51     $flagsrequired = 'execute_reports';
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 my $session = $cookie ? get_session($cookie->value) : undef;
67
68 my $filter;
69 if ( $input->param("filter_set") ) {
70     $filter = {};
71     $filter->{$_} = $input->param("filter_$_") foreach qw/date author keyword group subgroup/;
72     $session->param('report_filter', $filter) if $session;
73     $template->param( 'filter_set' => 1 );
74 }
75 elsif ($session) {
76     $filter = $session->param('report_filter');
77 }
78
79
80 my @errors = ();
81 if ( !$phase ) {
82     $template->param( 'start' => 1 );
83     # show welcome page
84 }
85 elsif ( $phase eq 'Build new' ) {
86     # build a new report
87     $template->param( 'build1' => 1 );
88     my $areas = get_report_areas();
89     $template->param(
90         'areas' => [map { id => $_->[0], name => $_->[1] }, @$areas],
91         'usecache' => $usecache,
92         'cache_expiry' => 300,
93         'public' => '0',
94     );
95 } elsif ( $phase eq 'Use saved' ) {
96
97     # use a saved report
98     # get list of reports and display them
99     my $group = $input->param('group');
100     my $subgroup = $input->param('subgroup');
101     $filter->{group} = $group;
102     $filter->{subgroup} = $subgroup;
103     $template->param(
104         'saved1' => 1,
105         'savedreports' => get_saved_reports($filter),
106         'usecache' => $usecache,
107         'groups_with_subgroups'=> groups_with_subgroups($group, $subgroup),
108     );
109 }
110
111 elsif ( $phase eq 'Delete Saved') {
112         
113         # delete a report from the saved reports list
114         my $id = $input->param('reports');
115         delete_report($id);
116     print $input->redirect("/cgi-bin/koha/reports/guided_reports.pl?phase=Use%20saved");
117         exit;
118 }               
119
120 elsif ( $phase eq 'Show SQL'){
121         
122     my $id = $input->param('reports');
123     my $report = get_saved_report($id);
124     $template->param(
125         'id'      => $id,
126         'reportname' => $report->{report_name},
127         'notes'      => $report->{notes},
128         'sql'     => $report->{savedsql},
129         'showsql' => 1,
130     );
131 }
132
133 elsif ( $phase eq 'Edit SQL'){
134     my $id = $input->param('reports');
135     my $report = get_saved_report($id);
136     my $group = $report->{report_group};
137     my $subgroup  = $report->{report_subgroup};
138     $template->param(
139         'sql'        => $report->{savedsql},
140         'reportname' => $report->{report_name},
141         'groups_with_subgroups' => groups_with_subgroups($group, $subgroup),
142         'notes'      => $report->{notes},
143         'id'         => $id,
144         'cache_expiry' => $report->{cache_expiry},
145         'public' => $report->{public},
146         'usecache' => $usecache,
147         'editsql'    => 1,
148     );
149 }
150
151 elsif ( $phase eq 'Update SQL'){
152     my $id         = $input->param('id');
153     my $sql        = $input->param('sql');
154     my $reportname = $input->param('reportname');
155     my $group      = $input->param('group');
156     my $subgroup   = $input->param('subgroup');
157     my $notes      = $input->param('notes');
158     my $cache_expiry = $input->param('cache_expiry');
159     my $cache_expiry_units = $input->param('cache_expiry_units');
160     my $public = $input->param('public');
161     my $save_anyway = $input->param('save_anyway');
162
163     my @errors;
164
165     # if we have the units, then we came from creating a report from SQL and thus need to handle converting units
166     if( $cache_expiry_units ){
167       if( $cache_expiry_units eq "minutes" ){
168         $cache_expiry *= 60;
169       } elsif( $cache_expiry_units eq "hours" ){
170         $cache_expiry *= 3600; # 60 * 60
171       } elsif( $cache_expiry_units eq "days" ){
172         $cache_expiry *= 86400; # 60 * 60 * 24
173       }
174     }
175     # check $cache_expiry isnt too large, Memcached::set requires it to be less than 30 days or it will be treated as if it were an absolute time stamp
176     if( $cache_expiry >= 2592000 ){
177       push @errors, {cache_expiry => $cache_expiry};
178     }
179
180     create_non_existing_group_and_subgroup($input, $group, $subgroup);
181
182     if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
183         push @errors, {sqlerr => $1};
184     }
185     elsif ($sql !~ /^(SELECT)/i) {
186         push @errors, {queryerr => 1};
187     }
188
189     if (@errors) {
190         $template->param(
191             'errors'    => \@errors,
192             'sql'       => $sql,
193         );
194     } else {
195
196         # Check defined SQL parameters for authorised value validity
197         my $problematic_authvals = ValidateSQLParameters($sql);
198
199         if ( scalar @$problematic_authvals > 0 && not $save_anyway ) {
200             # There's at least one problematic parameter, report to the
201             # GUI and provide all user input for further actions
202             $template->param(
203                 'id' => $id,
204                 'sql' => $sql,
205                 'reportname' => $reportname,
206                 'group' => $group,
207                 'subgroup' => $subgroup,
208                 'notes' => $notes,
209                 'cache_expiry' => $cache_expiry,
210                 'cache_expiry_units' => $cache_expiry_units,
211                 'public' => $public,
212                 'problematic_authvals' => $problematic_authvals,
213                 'warn_authval_problem' => 1,
214                 'phase_update' => 1
215             );
216
217         } else {
218             # No params problem found or asked to save anyway
219             update_sql( $id, {
220                     sql => $sql,
221                     name => $reportname,
222                     group => $group,
223                     subgroup => $subgroup,
224                     notes => $notes,
225                     cache_expiry => $cache_expiry,
226                     public => $public,
227                 } );
228             $template->param(
229                 'save_successful'       => 1,
230                 'reportname'            => $reportname,
231                 'id'                    => $id,
232             );
233         }
234     }
235 }
236
237 elsif ($phase eq 'retrieve results') {
238         my $id = $input->param('id');
239         my ($results,$name,$notes) = format_results($id);
240         # do something
241         $template->param(
242                 'retresults' => 1,
243                 'results' => $results,
244                 'name' => $name,
245                 'notes' => $notes,
246     );
247 }
248
249 elsif ( $phase eq 'Report on this Area' ) {
250     my $cache_expiry_units = $input->param('cache_expiry_units'),
251     my $cache_expiry = $input->param('cache_expiry');
252
253     # we need to handle converting units
254     if( $cache_expiry_units eq "minutes" ){
255       $cache_expiry *= 60;
256     } elsif( $cache_expiry_units eq "hours" ){
257       $cache_expiry *= 3600; # 60 * 60
258     } elsif( $cache_expiry_units eq "days" ){
259       $cache_expiry *= 86400; # 60 * 60 * 24
260     }
261     # check $cache_expiry isnt too large, Memcached::set requires it to be less than 30 days or it will be treated as if it were an absolute time stamp
262     if( $cache_expiry >= 2592000 ){ # oops, over the limit of 30 days
263       # report error to user
264       $template->param(
265         'cache_error' => 1,
266         'build1' => 1,
267         'areas'   => get_report_areas(),
268         'cache_expiry' => $cache_expiry,
269         'usecache' => $usecache,
270         'public' => $input->param('public'),
271       );
272     } else {
273       # they have choosen a new report and the area to report on
274       $template->param(
275           'build2' => 1,
276           'area'   => $input->param('area'),
277           'types'  => get_report_types(),
278           'cache_expiry' => $cache_expiry,
279           'public' => $input->param('public'),
280       );
281     }
282 }
283
284 elsif ( $phase eq 'Choose this type' ) {
285     # they have chosen type and area
286     # get area and type and pass them to the template
287     my $area = $input->param('area');
288     my $type = $input->param('types');
289     $template->param(
290         'build3' => 1,
291         'area'   => $area,
292         'type'   => $type,
293         columns  => get_columns($area,$input),
294         'cache_expiry' => $input->param('cache_expiry'),
295         'public' => $input->param('public'),
296     );
297 }
298
299 elsif ( $phase eq 'Choose these columns' ) {
300     # we now know type, area, and columns
301     # next step is the constraints
302     my $area    = $input->param('area');
303     my $type    = $input->param('type');
304     my @columns = $input->param('columns');
305     my $column  = join( ',', @columns );
306     $template->param(
307         'build4' => 1,
308         'area'   => $area,
309         'type'   => $type,
310         'column' => $column,
311         definitions => get_from_dictionary($area),
312         criteria    => get_criteria($area,$input),
313         'cache_expiry' => $input->param('cache_expiry'),
314         'cache_expiry_units' => $input->param('cache_expiry_units'),
315         'public' => $input->param('public'),
316     );
317 }
318
319 elsif ( $phase eq 'Choose these criteria' ) {
320     my $area     = $input->param('area');
321     my $type     = $input->param('type');
322     my $column   = $input->param('column');
323     my @definitions = $input->param('definition');
324     my $definition = join (',',@definitions);
325     my @criteria = $input->param('criteria_column');
326     my $query_criteria;
327     foreach my $crit (@criteria) {
328         my $value = $input->param( $crit . "_value" );
329
330         # If value is not defined, then it may be range values
331         if (!defined $value) {
332
333             my $fromvalue = $input->param( "from_" . $crit . "_value" );
334             my $tovalue   = $input->param( "to_"   . $crit . "_value" );
335
336             # If the range values are dates
337             if ($fromvalue =~ C4::Dates->regexp('syspref') && $tovalue =~ C4::Dates->regexp('syspref')) {
338                 $fromvalue = C4::Dates->new($fromvalue)->output("iso");
339                 $tovalue = C4::Dates->new($tovalue)->output("iso");
340             }
341
342             if ($fromvalue && $tovalue) {
343                 $query_criteria .= " AND $crit >= '$fromvalue' AND $crit <= '$tovalue'";
344             }
345
346         } else {
347
348             # If value is a date
349             if ($value =~ C4::Dates->regexp('syspref')) {
350                 $value = C4::Dates->new($value)->output("iso");
351             }
352             # don't escape runtime parameters, they'll be at runtime
353             if ($value =~ /<<.*>>/) {
354                 $query_criteria .= " AND $crit=$value";
355             } else {
356                 $query_criteria .= " AND $crit='$value'";
357             }
358         }
359     }
360     $template->param(
361         'build5'         => 1,
362         'area'           => $area,
363         'type'           => $type,
364         'column'         => $column,
365         'definition'     => $definition,
366         'criteriastring' => $query_criteria,
367         'cache_expiry' => $input->param('cache_expiry'),
368         'cache_expiry_units' => $input->param('cache_expiry_units'),
369         'public' => $input->param('public'),
370     );
371
372     # get columns
373     my @columns = split( ',', $column );
374     my @total_by;
375
376     # build structue for use by tmpl_loop to choose columns to order by
377     # need to do something about the order of the order :)
378         # we also want to use the %columns hash to get the plain english names
379     foreach my $col (@columns) {
380         my %total = (name => $col);
381         my @selects = map {+{ value => $_ }} (qw(sum min max avg count));
382         $total{'select'} = \@selects;
383         push @total_by, \%total;
384     }
385
386     $template->param( 'total_by' => \@total_by );
387 }
388
389 elsif ( $phase eq 'Choose these operations' ) {
390     my $area     = $input->param('area');
391     my $type     = $input->param('type');
392     my $column   = $input->param('column');
393     my $criteria = $input->param('criteria');
394         my $definition = $input->param('definition');
395     my @total_by = $input->param('total_by');
396     my $totals;
397     foreach my $total (@total_by) {
398         my $value = $input->param( $total . "_tvalue" );
399         $totals .= "$value($total),";
400     }
401
402     $template->param(
403         'build6'         => 1,
404         'area'           => $area,
405         'type'           => $type,
406         'column'         => $column,
407         'criteriastring' => $criteria,
408         'totals'         => $totals,
409         'definition'     => $definition,
410         'cache_expiry' => $input->param('cache_expiry'),
411         'public' => $input->param('public'),
412     );
413
414     # get columns
415     my @columns = split( ',', $column );
416     my @order_by;
417
418     # build structue for use by tmpl_loop to choose columns to order by
419     # need to do something about the order of the order :)
420     foreach my $col (@columns) {
421         my %order = (name => $col);
422         my @selects = map {+{ value => $_ }} (qw(asc desc));
423         $order{'select'} = \@selects;
424         push @order_by, \%order;
425     }
426
427     $template->param( 'order_by' => \@order_by );
428 }
429
430 elsif ( $phase eq 'Build report' ) {
431
432     # now we have all the info we need and can build the sql
433     my $area     = $input->param('area');
434     my $type     = $input->param('type');
435     my $column   = $input->param('column');
436     my $crit     = $input->param('criteria');
437     my $totals   = $input->param('totals');
438     my $definition = $input->param('definition');
439     my $query_criteria=$crit;
440     # split the columns up by ,
441     my @columns = split( ',', $column );
442     my @order_by = $input->param('order_by');
443
444     my $query_orderby;
445     foreach my $order (@order_by) {
446         my $value = $input->param( $order . "_ovalue" );
447         if ($query_orderby) {
448             $query_orderby .= ",$order $value";
449         }
450         else {
451             $query_orderby = " ORDER BY $order $value";
452         }
453     }
454
455     # get the sql
456     my $sql =
457       build_query( \@columns, $query_criteria, $query_orderby, $area, $totals, $definition );
458     $template->param(
459         'showreport' => 1,
460         'area'       => $area,
461         'sql'        => $sql,
462         'type'       => $type,
463         'cache_expiry' => $input->param('cache_expiry'),
464         'public' => $input->param('public'),
465     );
466 }
467
468 elsif ( $phase eq 'Save' ) {
469     # Save the report that has just been built
470     my $area           = $input->param('area');
471     my $sql  = $input->param('sql');
472     my $type = $input->param('type');
473     $template->param(
474         'save' => 1,
475         'area'  => $area,
476         'sql'  => $sql,
477         'type' => $type,
478         'cache_expiry' => $input->param('cache_expiry'),
479         'public' => $input->param('public'),
480         'groups_with_subgroups' => groups_with_subgroups($area), # in case we have a report group that matches area
481     );
482 }
483
484 elsif ( $phase eq 'Save Report' ) {
485     # save the sql pasted in by a user
486     my $area  = $input->param('area');
487     my $group = $input->param('group');
488     my $subgroup = $input->param('subgroup');
489     my $sql   = $input->param('sql');
490     my $name  = $input->param('reportname');
491     my $type  = $input->param('types');
492     my $notes = $input->param('notes');
493     my $cache_expiry = $input->param('cache_expiry');
494     my $cache_expiry_units = $input->param('cache_expiry_units');
495     my $public = $input->param('public');
496     my $save_anyway = $input->param('save_anyway');
497
498
499     # if we have the units, then we came from creating a report from SQL and thus need to handle converting units
500     if( $cache_expiry_units ){
501       if( $cache_expiry_units eq "minutes" ){
502         $cache_expiry *= 60;
503       } elsif( $cache_expiry_units eq "hours" ){
504         $cache_expiry *= 3600; # 60 * 60
505       } elsif( $cache_expiry_units eq "days" ){
506         $cache_expiry *= 86400; # 60 * 60 * 24
507       }
508     }
509     # check $cache_expiry isnt too large, Memcached::set requires it to be less than 30 days or it will be treated as if it were an absolute time stamp
510     if( $cache_expiry && $cache_expiry >= 2592000 ){
511       push @errors, {cache_expiry => $cache_expiry};
512     }
513
514     create_non_existing_group_and_subgroup($input, $group, $subgroup);
515
516     ## FIXME this is AFTER entering a name to save the report under
517     if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
518         push @errors, {sqlerr => $1};
519     }
520     elsif ($sql !~ /^(SELECT)/i) {
521         push @errors, {queryerr => "No SELECT"};
522     }
523
524     if (@errors) {
525         $template->param(
526             'errors'    => \@errors,
527             'sql'       => $sql,
528             'reportname'=> $name,
529             'type'      => $type,
530             'notes'     => $notes,
531             'cache_expiry' => $cache_expiry,
532             'public'    => $public,
533         );
534     } else {
535         # Check defined SQL parameters for authorised value validity
536         my $problematic_authvals = ValidateSQLParameters($sql);
537
538         if ( scalar @$problematic_authvals > 0 && not $save_anyway ) {
539             # There's at least one problematic parameter, report to the
540             # GUI and provide all user input for further actions
541             $template->param(
542                 'area' => $area,
543                 'group' =>  $group,
544                 'subgroup' => $subgroup,
545                 'sql' => $sql,
546                 'reportname' => $name,
547                 'type' => $type,
548                 'notes' => $notes,
549                 'cache_expiry' => $cache_expiry,
550                 'cache_expiry_units' => $cache_expiry_units,
551                 'public' => $public,
552                 'problematic_authvals' => $problematic_authvals,
553                 'warn_authval_problem' => 1,
554                 'phase_save' => 1
555             );
556         } else {
557             # No params problem found or asked to save anyway
558             my $id = save_report( {
559                     borrowernumber => $borrowernumber,
560                     sql            => $sql,
561                     name           => $name,
562                     area           => $area,
563                     group          => $group,
564                     subgroup       => $subgroup,
565                     type           => $type,
566                     notes          => $notes,
567                     cache_expiry   => $cache_expiry,
568                     public         => $public,
569                 } );
570             $template->param(
571                 'save_successful' => 1,
572                 'reportname'      => $name,
573                 'id'              => $id,
574             );
575         }
576     }
577 }
578
579 elsif ($phase eq 'Run this report'){
580     # execute a saved report
581     my $limit      = $input->param('limit') || 20;
582     my $offset     = 0;
583     my $report_id  = $input->param('reports');
584     my @sql_params = $input->param('sql_params');
585     # offset algorithm
586     if ($input->param('page')) {
587         $offset = ($input->param('page') - 1) * $limit;
588     }
589
590     $template->param(
591         'limit'   => $limit,
592         'report_id' => $report_id,
593     );
594
595     my ( $sql, $type, $name, $notes );
596     if (my $report = get_saved_report($report_id)) {
597         $sql   = $report->{savedsql};
598         $name  = $report->{report_name};
599         $notes = $report->{notes};
600
601         my @rows = ();
602         # if we have at least 1 parameter, and it's not filled, then don't execute but ask for parameters
603         if ($sql =~ /<</ && !@sql_params) {
604             # split on ??. Each odd (2,4,6,...) entry should be a parameter to fill
605             my @split = split /<<|>>/,$sql;
606             my @tmpl_parameters;
607             my @authval_errors;
608             for(my $i=0;$i<($#split/2);$i++) {
609                 my ($text,$authorised_value) = split /\|/,$split[$i*2+1];
610                 my $input;
611                 my $labelid;
612                 if ( not defined $authorised_value ) {
613                     # no authorised value input, provide a text box
614                     $input = "text";
615                 } elsif ( $authorised_value eq "date" ) {
616                     # require a date, provide a date picker
617                     $input = 'date';
618                 } else {
619                     # defined $authorised_value, and not 'date'
620                     my $dbh=C4::Context->dbh;
621                     my @authorised_values;
622                     my %authorised_lib;
623                     # builds list, depending on authorised value...
624                     if ( $authorised_value eq "branches" ) {
625                         my $branches = GetBranchesLoop();
626                         foreach my $thisbranch (@$branches) {
627                             push @authorised_values, $thisbranch->{value};
628                             $authorised_lib{$thisbranch->{value}} = $thisbranch->{branchname};
629                         }
630                     }
631                     elsif ( $authorised_value eq "itemtypes" ) {
632                         my $sth = $dbh->prepare("SELECT itemtype,description FROM itemtypes ORDER BY description");
633                         $sth->execute;
634                         while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
635                             push @authorised_values, $itemtype;
636                             $authorised_lib{$itemtype} = $description;
637                         }
638                     }
639                     elsif ( $authorised_value eq "cn_source" ) {
640                         my $class_sources = GetClassSources();
641                         my $default_source = C4::Context->preference("DefaultClassificationSource");
642                         foreach my $class_source (sort keys %$class_sources) {
643                             next unless $class_sources->{$class_source}->{'used'} or
644                                         ($class_source eq $default_source);
645                             push @authorised_values, $class_source;
646                             $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
647                         }
648                     }
649                     elsif ( $authorised_value eq "categorycode" ) {
650                         my $sth = $dbh->prepare("SELECT categorycode, description FROM categories ORDER BY description");
651                         $sth->execute;
652                         while ( my ( $categorycode, $description ) = $sth->fetchrow_array ) {
653                             push @authorised_values, $categorycode;
654                             $authorised_lib{$categorycode} = $description;
655                         }
656
657                         #---- "true" authorised value
658                     }
659                     else {
660                         if ( IsAuthorisedValueCategory($authorised_value) ) {
661                             my $query = '
662                             SELECT authorised_value,lib
663                             FROM authorised_values
664                             WHERE category=?
665                             ORDER BY lib
666                             ';
667                             my $authorised_values_sth = $dbh->prepare($query);
668                             $authorised_values_sth->execute( $authorised_value);
669
670                             while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
671                                 push @authorised_values, $value;
672                                 $authorised_lib{$value} = $lib;
673                                 # For item location, we show the code and the libelle
674                                 $authorised_lib{$value} = $lib;
675                             }
676                         } else {
677                             # not exists $authorised_value_categories{$authorised_value})
678                             push @authval_errors, {'entry' => $text,
679                                                    'auth_val' => $authorised_value };
680                             # tell the template there's an error
681                             $template->param( auth_val_error => 1 );
682                             # skip scrolling list creation and params push
683                             next;
684                         }
685                     }
686                     $labelid = $text;
687                     $labelid =~ s/\W//g;
688                     $input =CGI::scrolling_list(      # FIXME: factor out scrolling_list
689                         -name     => "sql_params",
690                         -id       => "sql_params_".$labelid,
691                         -values   => \@authorised_values,
692 #                     -default  => $value,
693                         -labels   => \%authorised_lib,
694                         -override => 1,
695                         -size     => 1,
696                         -multiple => 0,
697                         -tabindex => 1,
698                     );
699                 }
700
701                 push @tmpl_parameters, {'entry' => $text, 'input' => $input, 'labelid' => $labelid };
702             }
703             $template->param('sql'         => $sql,
704                             'name'         => $name,
705                             'sql_params'   => \@tmpl_parameters,
706                             'auth_val_errors'  => \@authval_errors,
707                             'enter_params' => 1,
708                             'reports'      => $report_id,
709                             );
710         } else {
711             # OK, we have parameters, or there are none, we run the report
712             # if there were parameters, replace before running
713             # split on ??. Each odd (2,4,6,...) entry should be a parameter to fill
714             my @split = split /<<|>>/,$sql;
715             my @tmpl_parameters;
716             for(my $i=0;$i<$#split/2;$i++) {
717                 my $quoted = C4::Context->dbh->quote($sql_params[$i]);
718                 # if there are special regexp chars, we must \ them
719                 $split[$i*2+1] =~ s/(\||\?|\.|\*|\(|\)|\%)/\\$1/g;
720                 $sql =~ s/<<$split[$i*2+1]>>/$quoted/;
721             }
722             my ($sth, $errors) = execute_query($sql, $offset, $limit);
723             my $total = nb_rows($sql) || 0;
724             unless ($sth) {
725                 die "execute_query failed to return sth for report $report_id: $sql";
726             } else {
727                 my $headers= header_cell_loop($sth);
728                 $template->param(header_row => $headers);
729                 while (my $row = $sth->fetchrow_arrayref()) {
730                     my @cells = map { +{ cell => $_ } } @$row;
731                     push @rows, { cells => \@cells };
732                 }
733             }
734
735             my $totpages = int($total/$limit) + (($total % $limit) > 0 ? 1 : 0);
736             my $url = "/cgi-bin/koha/reports/guided_reports.pl?reports=$report_id&amp;phase=Run%20this%20report&amp;limit=$limit";
737             if (@sql_params) {
738                 $url = join('&amp;sql_params=', $url, map { URI::Escape::uri_escape($_) } @sql_params);
739             }
740             $template->param(
741                 'results' => \@rows,
742                 'sql'     => $sql,
743                 'id'      => $report_id,
744                 'execute' => 1,
745                 'name'    => $name,
746                 'notes'   => $notes,
747                 'errors'  => $errors,
748                 'pagination_bar'  => pagination_bar($url, $totpages, $input->param('page')),
749                 'unlimited_total' => $total,
750                 'sql_params'      => \@sql_params,
751             );
752         }
753     }
754     else {
755         push @errors, { no_sql_for_id => $report_id };
756     }
757 }
758
759 elsif ($phase eq 'Export'){
760     binmode STDOUT, ':encoding(UTF-8)';
761
762         # export results to tab separated text or CSV
763         my $sql    = $input->param('sql');  # FIXME: use sql from saved report ID#, not new user-supplied SQL!
764     my $format = $input->param('format');
765         my ($sth, $q_errors) = execute_query($sql);
766     unless ($q_errors and @$q_errors) {
767         print $input->header(       -type => 'application/octet-stream',
768                                     -attachment=>"reportresults.$format"
769                             );
770         if ($format eq 'tab') {
771             print join("\t", header_cell_values($sth)), "\n";
772             while (my $row = $sth->fetchrow_arrayref()) {
773                 print join("\t", @$row), "\n";
774             }
775         } else {
776             my $csv = Text::CSV->new({binary => 1});
777             $csv or die "Text::CSV->new({binary => 1}) FAILED: " . Text::CSV->error_diag();
778             if ($csv->combine(header_cell_values($sth))) {
779                 print $csv->string(), "\n";
780             } else {
781                 push @$q_errors, { combine => 'HEADER ROW: ' . $csv->error_diag() } ;
782             }
783             while (my $row = $sth->fetchrow_arrayref()) {
784                 if ($csv->combine(@$row)) {
785                     print $csv->string(), "\n"; 
786                 } else {
787                     push @$q_errors, { combine => $csv->error_diag() } ;
788                 }
789             }
790         }
791         foreach my $err (@$q_errors, @errors) {
792             print "# ERROR: " . (map {$_ . ": " . $err->{$_}} keys %$err) . "\n";
793         }   # here we print all the non-fatal errors at the end.  Not super smooth, but better than nothing.
794         exit;
795     }
796     $template->param(
797         'sql'           => $sql,
798         'execute'       => 1,
799         'name'          => 'Error exporting report!',
800         'notes'         => '',
801         'errors'        => $q_errors,
802     );
803 }
804
805 elsif ( $phase eq 'Create report from SQL' ) {
806
807     my ($group, $subgroup);
808     # allow the user to paste in sql
809     if ( $input->param('sql') ) {
810         $group = $input->param('report_group');
811         $subgroup  = $input->param('report_subgroup');
812         $template->param(
813             'sql'           => $input->param('sql') // '',
814             'reportname'    => $input->param('reportname') // '',
815             'notes'         => $input->param('notes') // '',
816         );
817     }
818     $template->param(
819         'create' => 1,
820         'groups_with_subgroups' => groups_with_subgroups($group, $subgroup),
821         'public' => '0',
822         'cache_expiry' => 300,
823         'usecache' => $usecache,
824     );
825 }
826
827 elsif ($phase eq 'Create Compound Report'){
828         $template->param( 'savedreports' => get_saved_reports(),
829                 'compound' => 1,
830         );
831 }
832
833 elsif ($phase eq 'Save Compound'){
834     my $master    = $input->param('master');
835         my $subreport = $input->param('subreport');
836         my ($mastertables,$subtables) = create_compound($master,$subreport);
837         $template->param( 'save_compound' => 1,
838                 master=>$mastertables,
839                 subsql=>$subtables
840         );
841 }
842
843 # pass $sth, get back an array of names for the column headers
844 sub header_cell_values {
845     my $sth = shift or return ();
846     my @cols;
847     foreach my $c (@{$sth->{NAME}}) {
848         #FIXME apparently DBI still needs a utf8 fix for this?
849         utf8::decode($c);
850         push @cols, $c;
851     }
852     return @cols;
853 }
854
855 # pass $sth, get back a TMPL_LOOP-able set of names for the column headers
856 sub header_cell_loop {
857     my @headers = map { +{ cell => $_ } } header_cell_values (shift);
858     return \@headers;
859 }
860
861 foreach (1..6) {
862      $template->{VARS}->{'build' . $_} and $template->{VARS}->{'buildx' . $_} and last;
863 }
864 $template->param(   'referer' => $input->referer(),
865                 );
866
867 output_html_with_http_headers $input, $cookie, $template->output;
868
869 sub groups_with_subgroups {
870     my ($group, $subgroup) = @_;
871
872     my $groups_with_subgroups = get_report_groups();
873     my @g_sg;
874     my @sorted_keys = sort {
875         $groups_with_subgroups->{$a}->{name} cmp $groups_with_subgroups->{$b}->{name}
876     } keys %$groups_with_subgroups;
877     foreach my $g_id (@sorted_keys) {
878         my $v = $groups_with_subgroups->{$g_id};
879         my @subgroups;
880         if (my $sg = $v->{subgroups}) {
881             foreach my $sg_id (sort { $sg->{$a} cmp $sg->{$b} } keys %$sg) {
882                 push @subgroups, {
883                     id => $sg_id,
884                     name => $sg->{$sg_id},
885                     selected => ($group && $g_id eq $group && $subgroup && $sg_id eq $subgroup ),
886                 };
887             }
888         }
889         push @g_sg, {
890             id => $g_id,
891             name => $v->{name},
892             selected => ($group && $g_id eq $group),
893             subgroups => \@subgroups,
894         };
895     }
896     return \@g_sg;
897 }
898
899 sub create_non_existing_group_and_subgroup {
900     my ($input, $group, $subgroup) = @_;
901
902     if (defined $group and $group ne '') {
903         my $report_groups = C4::Reports::Guided::get_report_groups;
904         if (not exists $report_groups->{$group}) {
905             my $groupdesc = $input->param('groupdesc') // $group;
906             C4::Koha::AddAuthorisedValue('REPORT_GROUP', $group, $groupdesc);
907         }
908         if (defined $subgroup and $subgroup ne '') {
909             if (not exists $report_groups->{$group}->{subgroups}->{$subgroup}) {
910                 my $subgroupdesc = $input->param('subgroupdesc') // $subgroup;
911                 C4::Koha::AddAuthorisedValue('REPORT_SUBGROUP', $subgroup, $subgroupdesc, $group);
912             }
913         }
914     }
915 }