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