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