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