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