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