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