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