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