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