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