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