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