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