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