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