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