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