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