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