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