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