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