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