Bug 17590 - Exporting reports as CSV with 'delimiter' SysPref set to 'tabulation...
[koha.git] / reports / guided_reports.pl
blobeb43fff799c4ef1e7ed8774a3e099dfff0f7a42e
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::Koha qw/GetFrameworksLoop/;
32 use C4::Branch;
33 use C4::Context;
34 use C4::Log;
35 use Koha::DateUtils qw/dt_from_string output_pref/;
36 use Koha::AuthorisedValue;
37 use Koha::AuthorisedValues;
39 =head1 NAME
41 guided_reports.pl
43 =head1 DESCRIPTION
45 Script to control the guided report creation
47 =cut
49 my $input = new CGI;
50 my $usecache = C4::Context->ismemcached;
52 my $phase = $input->param('phase') // '';
53 my $flagsrequired;
54 if ( $phase eq 'Build new' or $phase eq 'Delete Saved' ) {
55 $flagsrequired = 'create_reports';
57 elsif ( $phase eq 'Use saved' ) {
58 $flagsrequired = 'execute_reports';
59 } else {
60 $flagsrequired = '*';
63 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
65 template_name => "reports/guided_reports_start.tt",
66 query => $input,
67 type => "intranet",
68 authnotrequired => 0,
69 flagsrequired => { reports => $flagsrequired },
70 debug => 1,
73 my $session = $cookie ? get_session($cookie->value) : undef;
75 my $filter;
76 if ( $input->param("filter_set") or $input->param('clear_filters') ) {
77 $filter = {};
78 $filter->{$_} = $input->param("filter_$_") foreach qw/date author keyword group subgroup/;
79 $session->param('report_filter', $filter) if $session;
80 $template->param( 'filter_set' => 1 );
82 elsif ($session and not $input->param('clear_filters')) {
83 $filter = $session->param('report_filter');
87 my @errors = ();
88 if ( !$phase ) {
89 $template->param( 'start' => 1 );
90 # show welcome page
92 elsif ( $phase eq 'Build new' ) {
93 # build a new report
94 $template->param( 'build1' => 1 );
95 $template->param(
96 'areas' => get_report_areas(),
97 'usecache' => $usecache,
98 'cache_expiry' => 300,
99 'public' => '0',
101 } elsif ( $phase eq 'Use saved' ) {
103 # use a saved report
104 # get list of reports and display them
105 my $group = $input->param('group');
106 my $subgroup = $input->param('subgroup');
107 $filter->{group} = $group;
108 $filter->{subgroup} = $subgroup;
109 $template->param(
110 'saved1' => 1,
111 'savedreports' => get_saved_reports($filter),
112 'usecache' => $usecache,
113 'groups_with_subgroups'=> groups_with_subgroups($group, $subgroup),
114 filters => $filter,
118 elsif ( $phase eq 'Delete Multiple') {
119 my @ids = $input->multi_param('ids');
120 delete_report( @ids );
121 print $input->redirect("/cgi-bin/koha/reports/guided_reports.pl?phase=Use%20saved");
122 exit;
125 elsif ( $phase eq 'Delete Saved') {
127 # delete a report from the saved reports list
128 my $ids = $input->param('reports');
129 delete_report($ids);
130 print $input->redirect("/cgi-bin/koha/reports/guided_reports.pl?phase=Use%20saved");
131 exit;
134 elsif ( $phase eq 'Show SQL'){
136 my $id = $input->param('reports');
137 my $report = get_saved_report($id);
138 $template->param(
139 'id' => $id,
140 'reportname' => $report->{report_name},
141 'notes' => $report->{notes},
142 'sql' => $report->{savedsql},
143 'showsql' => 1,
147 elsif ( $phase eq 'Edit SQL'){
148 my $id = $input->param('reports');
149 my $report = get_saved_report($id);
150 my $group = $report->{report_group};
151 my $subgroup = $report->{report_subgroup};
152 $template->param(
153 'sql' => $report->{savedsql},
154 'reportname' => $report->{report_name},
155 'groups_with_subgroups' => groups_with_subgroups($group, $subgroup),
156 'notes' => $report->{notes},
157 'id' => $id,
158 'cache_expiry' => $report->{cache_expiry},
159 'public' => $report->{public},
160 'usecache' => $usecache,
161 'editsql' => 1,
165 elsif ( $phase eq 'Update SQL'){
166 my $id = $input->param('id');
167 my $sql = $input->param('sql');
168 my $reportname = $input->param('reportname');
169 my $group = $input->param('group');
170 my $subgroup = $input->param('subgroup');
171 my $notes = $input->param('notes');
172 my $cache_expiry = $input->param('cache_expiry');
173 my $cache_expiry_units = $input->param('cache_expiry_units');
174 my $public = $input->param('public');
175 my $save_anyway = $input->param('save_anyway');
177 my @errors;
179 # if we have the units, then we came from creating a report from SQL and thus need to handle converting units
180 if( $cache_expiry_units ){
181 if( $cache_expiry_units eq "minutes" ){
182 $cache_expiry *= 60;
183 } elsif( $cache_expiry_units eq "hours" ){
184 $cache_expiry *= 3600; # 60 * 60
185 } elsif( $cache_expiry_units eq "days" ){
186 $cache_expiry *= 86400; # 60 * 60 * 24
189 # 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
190 if( $cache_expiry >= 2592000 ){
191 push @errors, {cache_expiry => $cache_expiry};
194 create_non_existing_group_and_subgroup($input, $group, $subgroup);
196 if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
197 push @errors, {sqlerr => $1};
199 elsif ($sql !~ /^(SELECT)/i) {
200 push @errors, {queryerr => "No SELECT"};
203 if (@errors) {
204 $template->param(
205 'errors' => \@errors,
206 'sql' => $sql,
208 } else {
210 # Check defined SQL parameters for authorised value validity
211 my $problematic_authvals = ValidateSQLParameters($sql);
213 if ( scalar @$problematic_authvals > 0 && not $save_anyway ) {
214 # There's at least one problematic parameter, report to the
215 # GUI and provide all user input for further actions
216 $template->param(
217 'id' => $id,
218 'sql' => $sql,
219 'reportname' => $reportname,
220 'group' => $group,
221 'subgroup' => $subgroup,
222 'notes' => $notes,
223 'public' => $public,
224 'problematic_authvals' => $problematic_authvals,
225 'warn_authval_problem' => 1,
226 'phase_update' => 1
229 } else {
230 # No params problem found or asked to save anyway
231 update_sql( $id, {
232 sql => $sql,
233 name => $reportname,
234 group => $group,
235 subgroup => $subgroup,
236 notes => $notes,
237 public => $public,
238 cache_expiry => $cache_expiry,
239 } );
240 $template->param(
241 'save_successful' => 1,
242 'reportname' => $reportname,
243 'id' => $id,
245 logaction( "REPORTS", "MODIFY", $id, "$reportname | $sql" ) if C4::Context->preference("ReportsLog");
247 if ( $usecache ) {
248 $template->param(
249 cache_expiry => $cache_expiry,
250 cache_expiry_units => $cache_expiry_units,
256 elsif ($phase eq 'retrieve results') {
257 my $id = $input->param('id');
258 my ($results,$name,$notes) = format_results($id);
259 # do something
260 $template->param(
261 'retresults' => 1,
262 'results' => $results,
263 'name' => $name,
264 'notes' => $notes,
268 elsif ( $phase eq 'Report on this Area' ) {
269 my $cache_expiry_units = $input->param('cache_expiry_units'),
270 my $cache_expiry = $input->param('cache_expiry');
272 # we need to handle converting units
273 if( $cache_expiry_units eq "minutes" ){
274 $cache_expiry *= 60;
275 } elsif( $cache_expiry_units eq "hours" ){
276 $cache_expiry *= 3600; # 60 * 60
277 } elsif( $cache_expiry_units eq "days" ){
278 $cache_expiry *= 86400; # 60 * 60 * 24
280 # 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
281 if( $cache_expiry >= 2592000 ){ # oops, over the limit of 30 days
282 # report error to user
283 $template->param(
284 'cache_error' => 1,
285 'build1' => 1,
286 'areas' => get_report_areas(),
287 'cache_expiry' => $cache_expiry,
288 'usecache' => $usecache,
289 'public' => scalar $input->param('public'),
291 } else {
292 # they have choosen a new report and the area to report on
293 $template->param(
294 'build2' => 1,
295 'area' => scalar $input->param('area'),
296 'types' => get_report_types(),
297 'cache_expiry' => $cache_expiry,
298 'public' => scalar $input->param('public'),
303 elsif ( $phase eq 'Choose this type' ) {
304 # they have chosen type and area
305 # get area and type and pass them to the template
306 my $area = $input->param('area');
307 my $type = $input->param('types');
308 $template->param(
309 'build3' => 1,
310 'area' => $area,
311 'type' => $type,
312 columns => get_columns($area,$input),
313 'cache_expiry' => scalar $input->param('cache_expiry'),
314 'public' => scalar $input->param('public'),
318 elsif ( $phase eq 'Choose these columns' ) {
319 # we now know type, area, and columns
320 # next step is the constraints
321 my $area = $input->param('area');
322 my $type = $input->param('type');
323 my @columns = $input->multi_param('columns');
324 my $column = join( ',', @columns );
326 $template->param(
327 'build4' => 1,
328 'area' => $area,
329 'type' => $type,
330 'column' => $column,
331 definitions => get_from_dictionary($area),
332 criteria => get_criteria($area,$input),
333 'public' => scalar $input->param('public'),
335 if ( $usecache ) {
336 $template->param(
337 cache_expiry => scalar $input->param('cache_expiry'),
338 cache_expiry_units => scalar $input->param('cache_expiry_units'),
344 elsif ( $phase eq 'Choose these criteria' ) {
345 my $area = $input->param('area');
346 my $type = $input->param('type');
347 my $column = $input->param('column');
348 my @definitions = $input->multi_param('definition');
349 my $definition = join (',',@definitions);
350 my @criteria = $input->multi_param('criteria_column');
351 my $query_criteria;
352 foreach my $crit (@criteria) {
353 my $value = $input->param( $crit . "_value" );
355 # If value is not defined, then it may be range values
356 if (!defined $value) {
358 my $fromvalue = $input->param( "from_" . $crit . "_value" );
359 my $tovalue = $input->param( "to_" . $crit . "_value" );
361 # If the range values are dates
362 my $fromvalue_dt;
363 $fromvalue_dt = eval { dt_from_string( $fromvalue ); } if ( $fromvalue );
364 my $tovalue_dt;
365 $tovalue_dt = eval { dt_from_string( $tovalue ); } if ($tovalue);
366 if ( $fromvalue_dt && $tovalue_dt ) {
367 $fromvalue = output_pref( { dt => dt_from_string( $fromvalue_dt ), dateonly => 1, dateformat => 'iso' } );
368 $tovalue = output_pref( { dt => dt_from_string( $tovalue_dt ), dateonly => 1, dateformat => 'iso' } );
371 if ($fromvalue && $tovalue) {
372 $query_criteria .= " AND $crit >= '$fromvalue' AND $crit <= '$tovalue'";
375 } else {
377 # If value is a date
378 my $value_dt;
379 $value_dt = eval { dt_from_string( $value ); } if ( $value );
380 if ( $value_dt ) {
381 $value = output_pref( { dt => dt_from_string( $value_dt ), dateonly => 1, dateformat => 'iso' } );
383 # don't escape runtime parameters, they'll be at runtime
384 if ($value =~ /<<.*>>/) {
385 $query_criteria .= " AND $crit=$value";
386 } else {
387 $query_criteria .= " AND $crit='$value'";
391 $template->param(
392 'build5' => 1,
393 'area' => $area,
394 'type' => $type,
395 'column' => $column,
396 'definition' => $definition,
397 'criteriastring' => $query_criteria,
398 'public' => scalar $input->param('public'),
400 if ( $usecache ) {
401 $template->param(
402 cache_expiry => scalar $input->param('cache_expiry'),
403 cache_expiry_units => scalar $input->param('cache_expiry_units'),
407 # get columns
408 my @columns = split( ',', $column );
409 my @total_by;
411 # build structue for use by tmpl_loop to choose columns to order by
412 # need to do something about the order of the order :)
413 # we also want to use the %columns hash to get the plain english names
414 foreach my $col (@columns) {
415 my %total = (name => $col);
416 my @selects = map {+{ value => $_ }} (qw(sum min max avg count));
417 $total{'select'} = \@selects;
418 push @total_by, \%total;
421 $template->param( 'total_by' => \@total_by );
424 elsif ( $phase eq 'Choose these operations' ) {
425 my $area = $input->param('area');
426 my $type = $input->param('type');
427 my $column = $input->param('column');
428 my $criteria = $input->param('criteria');
429 my $definition = $input->param('definition');
430 my @total_by = $input->multi_param('total_by');
431 my $totals;
432 foreach my $total (@total_by) {
433 my $value = $input->param( $total . "_tvalue" );
434 $totals .= "$value($total),";
437 $template->param(
438 'build6' => 1,
439 'area' => $area,
440 'type' => $type,
441 'column' => $column,
442 'criteriastring' => $criteria,
443 'totals' => $totals,
444 'definition' => $definition,
445 'cache_expiry' => scalar $input->param('cache_expiry'),
446 'public' => scalar $input->param('public'),
449 # get columns
450 my @columns = split( ',', $column );
451 my @order_by;
453 # build structue for use by tmpl_loop to choose columns to order by
454 # need to do something about the order of the order :)
455 foreach my $col (@columns) {
456 my %order = (name => $col);
457 my @selects = map {+{ value => $_ }} (qw(asc desc));
458 $order{'select'} = \@selects;
459 push @order_by, \%order;
462 $template->param( 'order_by' => \@order_by );
465 elsif ( $phase eq 'Build report' ) {
467 # now we have all the info we need and can build the sql
468 my $area = $input->param('area');
469 my $type = $input->param('type');
470 my $column = $input->param('column');
471 my $crit = $input->param('criteria');
472 my $totals = $input->param('totals');
473 my $definition = $input->param('definition');
474 my $query_criteria=$crit;
475 # split the columns up by ,
476 my @columns = split( ',', $column );
477 my @order_by = $input->multi_param('order_by');
479 my $query_orderby;
480 foreach my $order (@order_by) {
481 my $value = $input->param( $order . "_ovalue" );
482 if ($query_orderby) {
483 $query_orderby .= ",$order $value";
485 else {
486 $query_orderby = " ORDER BY $order $value";
490 # get the sql
491 my $sql =
492 build_query( \@columns, $query_criteria, $query_orderby, $area, $totals, $definition );
493 $template->param(
494 'showreport' => 1,
495 'area' => $area,
496 'sql' => $sql,
497 'type' => $type,
498 'cache_expiry' => scalar $input->param('cache_expiry'),
499 'public' => scalar $input->param('public'),
503 elsif ( $phase eq 'Save' ) {
504 # Save the report that has just been built
505 my $area = $input->param('area');
506 my $sql = $input->param('sql');
507 my $type = $input->param('type');
508 $template->param(
509 'save' => 1,
510 'area' => $area,
511 'sql' => $sql,
512 'type' => $type,
513 'cache_expiry' => scalar $input->param('cache_expiry'),
514 'public' => scalar $input->param('public'),
515 'groups_with_subgroups' => groups_with_subgroups($area), # in case we have a report group that matches area
519 elsif ( $phase eq 'Save Report' ) {
520 # save the sql pasted in by a user
521 my $area = $input->param('area');
522 my $group = $input->param('group');
523 my $subgroup = $input->param('subgroup');
524 my $sql = $input->param('sql');
525 my $name = $input->param('reportname');
526 my $type = $input->param('types');
527 my $notes = $input->param('notes');
528 my $cache_expiry = $input->param('cache_expiry');
529 my $cache_expiry_units = $input->param('cache_expiry_units');
530 my $public = $input->param('public');
531 my $save_anyway = $input->param('save_anyway');
534 # if we have the units, then we came from creating a report from SQL and thus need to handle converting units
535 if( $cache_expiry_units ){
536 if( $cache_expiry_units eq "minutes" ){
537 $cache_expiry *= 60;
538 } elsif( $cache_expiry_units eq "hours" ){
539 $cache_expiry *= 3600; # 60 * 60
540 } elsif( $cache_expiry_units eq "days" ){
541 $cache_expiry *= 86400; # 60 * 60 * 24
544 # 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
545 if( $cache_expiry && $cache_expiry >= 2592000 ){
546 push @errors, {cache_expiry => $cache_expiry};
549 create_non_existing_group_and_subgroup($input, $group, $subgroup);
551 ## FIXME this is AFTER entering a name to save the report under
552 if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
553 push @errors, {sqlerr => $1};
555 elsif ($sql !~ /^(SELECT)/i) {
556 push @errors, {queryerr => "No SELECT"};
559 if (@errors) {
560 $template->param(
561 'errors' => \@errors,
562 'sql' => $sql,
563 'reportname'=> $name,
564 'type' => $type,
565 'notes' => $notes,
566 'cache_expiry' => $cache_expiry,
567 'public' => $public,
569 } else {
570 # Check defined SQL parameters for authorised value validity
571 my $problematic_authvals = ValidateSQLParameters($sql);
573 if ( scalar @$problematic_authvals > 0 && not $save_anyway ) {
574 # There's at least one problematic parameter, report to the
575 # GUI and provide all user input for further actions
576 $template->param(
577 'area' => $area,
578 'group' => $group,
579 'subgroup' => $subgroup,
580 'sql' => $sql,
581 'reportname' => $name,
582 'type' => $type,
583 'notes' => $notes,
584 'public' => $public,
585 'problematic_authvals' => $problematic_authvals,
586 'warn_authval_problem' => 1,
587 'phase_save' => 1
589 if ( $usecache ) {
590 $template->param(
591 cache_expiry => $cache_expiry,
592 cache_expiry_units => $cache_expiry_units,
595 } else {
596 # No params problem found or asked to save anyway
597 my $id = save_report( {
598 borrowernumber => $borrowernumber,
599 sql => $sql,
600 name => $name,
601 area => $area,
602 group => $group,
603 subgroup => $subgroup,
604 type => $type,
605 notes => $notes,
606 cache_expiry => $cache_expiry,
607 public => $public,
608 } );
609 logaction( "REPORTS", "ADD", $id, "$name | $sql" ) if C4::Context->preference("ReportsLog");
610 $template->param(
611 'save_successful' => 1,
612 'reportname' => $name,
613 'id' => $id,
619 elsif ($phase eq 'Run this report'){
620 # execute a saved report
621 my $limit = $input->param('limit') || 20;
622 my $offset = 0;
623 my $report_id = $input->param('reports');
624 my @sql_params = $input->multi_param('sql_params');
625 # offset algorithm
626 if ($input->param('page')) {
627 $offset = ($input->param('page') - 1) * $limit;
630 $template->param(
631 'limit' => $limit,
632 'report_id' => $report_id,
635 my ( $sql, $original_sql, $type, $name, $notes );
636 if (my $report = get_saved_report($report_id)) {
637 $sql = $original_sql = $report->{savedsql};
638 $name = $report->{report_name};
639 $notes = $report->{notes};
641 my @rows = ();
642 # if we have at least 1 parameter, and it's not filled, then don't execute but ask for parameters
643 if ($sql =~ /<</ && !@sql_params) {
644 # split on ??. Each odd (2,4,6,...) entry should be a parameter to fill
645 my @split = split /<<|>>/,$sql;
646 my @tmpl_parameters;
647 my @authval_errors;
648 for(my $i=0;$i<($#split/2);$i++) {
649 my ($text,$authorised_value) = split /\|/,$split[$i*2+1];
650 my $input;
651 my $labelid;
652 if ( not defined $authorised_value ) {
653 # no authorised value input, provide a text box
654 $input = "text";
655 } elsif ( $authorised_value eq "date" ) {
656 # require a date, provide a date picker
657 $input = 'date';
658 } else {
659 # defined $authorised_value, and not 'date'
660 my $dbh=C4::Context->dbh;
661 my @authorised_values;
662 my %authorised_lib;
663 # builds list, depending on authorised value...
664 if ( $authorised_value eq "branches" ) {
665 my $branches = GetBranchesLoop();
666 foreach my $thisbranch (@$branches) {
667 push @authorised_values, $thisbranch->{value};
668 $authorised_lib{$thisbranch->{value}} = $thisbranch->{branchname};
671 elsif ( $authorised_value eq "itemtypes" ) {
672 my $sth = $dbh->prepare("SELECT itemtype,description FROM itemtypes ORDER BY description");
673 $sth->execute;
674 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
675 push @authorised_values, $itemtype;
676 $authorised_lib{$itemtype} = $description;
679 elsif ( $authorised_value eq "biblio_framework" ) {
680 my $frameworks = GetFrameworksLoop();
681 my $default_source = '';
682 push @authorised_values,$default_source;
683 $authorised_lib{$default_source} = 'Default';
684 foreach my $framework (@$frameworks) {
685 push @authorised_values, $framework->{value};
686 $authorised_lib{$framework->{value}} = $framework->{description};
689 elsif ( $authorised_value eq "cn_source" ) {
690 my $class_sources = GetClassSources();
691 my $default_source = C4::Context->preference("DefaultClassificationSource");
692 foreach my $class_source (sort keys %$class_sources) {
693 next unless $class_sources->{$class_source}->{'used'} or
694 ($class_source eq $default_source);
695 push @authorised_values, $class_source;
696 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
699 elsif ( $authorised_value eq "categorycode" ) {
700 my $sth = $dbh->prepare("SELECT categorycode, description FROM categories ORDER BY description");
701 $sth->execute;
702 while ( my ( $categorycode, $description ) = $sth->fetchrow_array ) {
703 push @authorised_values, $categorycode;
704 $authorised_lib{$categorycode} = $description;
707 #---- "true" authorised value
709 else {
710 if ( Koha::AuthorisedValues->search({ category => $authorised_value })->count ) {
711 my $query = '
712 SELECT authorised_value,lib
713 FROM authorised_values
714 WHERE category=?
715 ORDER BY lib
717 my $authorised_values_sth = $dbh->prepare($query);
718 $authorised_values_sth->execute( $authorised_value);
720 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
721 push @authorised_values, $value;
722 $authorised_lib{$value} = $lib;
723 # For item location, we show the code and the libelle
724 $authorised_lib{$value} = $lib;
726 } else {
727 # not exists $authorised_value_categories{$authorised_value})
728 push @authval_errors, {'entry' => $text,
729 'auth_val' => $authorised_value };
730 # tell the template there's an error
731 $template->param( auth_val_error => 1 );
732 # skip scrolling list creation and params push
733 next;
736 $labelid = $text;
737 $labelid =~ s/\W//g;
738 $input = {
739 name => "sql_params",
740 id => "sql_params_".$labelid,
741 values => \@authorised_values,
742 labels => \%authorised_lib,
746 push @tmpl_parameters, {'entry' => $text, 'input' => $input, 'labelid' => $labelid };
748 $template->param('sql' => $sql,
749 'name' => $name,
750 'sql_params' => \@tmpl_parameters,
751 'auth_val_errors' => \@authval_errors,
752 'enter_params' => 1,
753 'reports' => $report_id,
755 } else {
756 # OK, we have parameters, or there are none, we run the report
757 # if there were parameters, replace before running
758 # split on ??. Each odd (2,4,6,...) entry should be a parameter to fill
759 my @split = split /<<|>>/,$sql;
760 my @tmpl_parameters;
761 for(my $i=0;$i<$#split/2;$i++) {
762 my $quoted = $sql_params[$i];
763 # if there are special regexp chars, we must \ them
764 $split[$i*2+1] =~ s/(\||\?|\.|\*|\(|\)|\%)/\\$1/g;
765 if ($split[$i*2+1] =~ /\|\s*date\s*$/) {
766 $quoted = output_pref({ dt => dt_from_string($quoted), dateformat => 'iso', dateonly => 1 }) if $quoted;
768 $quoted = C4::Context->dbh->quote($quoted);
769 $sql =~ s/<<$split[$i*2+1]>>/$quoted/;
771 my ($sth, $errors) = execute_query($sql, $offset, $limit);
772 my $total = nb_rows($sql) || 0;
773 unless ($sth) {
774 die "execute_query failed to return sth for report $report_id: $sql";
775 } else {
776 my $headers = header_cell_loop($sth);
777 $template->param(header_row => $headers);
778 while (my $row = $sth->fetchrow_arrayref()) {
779 my @cells = map { +{ cell => $_ } } @$row;
780 push @rows, { cells => \@cells };
784 my $totpages = int($total/$limit) + (($total % $limit) > 0 ? 1 : 0);
785 my $url = "/cgi-bin/koha/reports/guided_reports.pl?reports=$report_id&amp;phase=Run%20this%20report&amp;limit=$limit";
786 if (@sql_params) {
787 $url = join('&amp;sql_params=', $url, map { URI::Escape::uri_escape_utf8($_) } @sql_params);
789 $template->param(
790 'results' => \@rows,
791 'sql' => $sql,
792 original_sql => $original_sql,
793 'id' => $report_id,
794 'execute' => 1,
795 'name' => $name,
796 'notes' => $notes,
797 'errors' => defined($errors) ? [ $errors ] : undef,
798 'pagination_bar' => pagination_bar($url, $totpages, $input->param('page')),
799 'unlimited_total' => $total,
800 'sql_params' => \@sql_params,
804 else {
805 push @errors, { no_sql_for_id => $report_id };
809 elsif ($phase eq 'Export'){
811 # export results to tab separated text or CSV
812 my $sql = $input->param('sql'); # FIXME: use sql from saved report ID#, not new user-supplied SQL!
813 my $format = $input->param('format');
814 my $reportname = $input->param('reportname');
815 my $reportfilename = $reportname ? "$reportname-reportresults.$format" : "reportresults.$format" ;
816 my ($sth, $q_errors) = execute_query($sql);
817 unless ($q_errors and @$q_errors) {
818 my ( $type, $content );
819 if ($format eq 'tab') {
820 $type = 'application/octet-stream';
821 $content .= join("\t", header_cell_values($sth)) . "\n";
822 $content = Encode::decode('UTF-8', $content);
823 while (my $row = $sth->fetchrow_arrayref()) {
824 $content .= join("\t", @$row) . "\n";
826 } else {
827 my $delimiter = C4::Context->preference('delimiter') || ',';
828 if ( $format eq 'csv' ) {
829 $delimiter = "\t" if $delimiter eq 'tabulation';
830 $type = 'application/csv';
831 my $csv = Text::CSV::Encoded->new({ encoding_out => 'UTF-8', sep_char => $delimiter});
832 $csv or die "Text::CSV::Encoded->new({binary => 1}) FAILED: " . Text::CSV::Encoded->error_diag();
833 if ($csv->combine(header_cell_values($sth))) {
834 $content .= Encode::decode('UTF-8', $csv->string()) . "\n";
835 } else {
836 push @$q_errors, { combine => 'HEADER ROW: ' . $csv->error_diag() } ;
838 while (my $row = $sth->fetchrow_arrayref()) {
839 if ($csv->combine(@$row)) {
840 $content .= $csv->string() . "\n";
841 } else {
842 push @$q_errors, { combine => $csv->error_diag() } ;
846 elsif ( $format eq 'ods' ) {
847 $type = 'application/vnd.oasis.opendocument.spreadsheet';
848 my $ods_fh = File::Temp->new( UNLINK => 0 );
849 my $ods_filepath = $ods_fh->filename;
851 use OpenOffice::OODoc;
852 my $tmpdir = dirname $ods_filepath;
853 odfWorkingDirectory( $tmpdir );
854 my $container = odfContainer( $ods_filepath, create => 'spreadsheet' );
855 my $doc = odfDocument (
856 container => $container,
857 part => 'content'
859 my $table = $doc->getTable(0);
860 my @headers = header_cell_values( $sth );
861 my $rows = $sth->fetchall_arrayref();
862 my ( $nb_rows, $nb_cols ) = ( 0, 0 );
863 $nb_rows = @$rows;
864 $nb_cols = @headers;
865 $doc->expandTable( $table, $nb_rows + 1, $nb_cols );
867 my $row = $doc->getRow( $table, 0 );
868 my $j = 0;
869 for my $header ( @headers ) {
870 $doc->cellValue( $row, $j, $header );
871 $j++;
873 my $i = 1;
874 for ( @$rows ) {
875 $row = $doc->getRow( $table, $i );
876 for ( my $j = 0 ; $j < $nb_cols ; $j++ ) {
877 my $value = Encode::encode( 'UTF8', $rows->[$i - 1][$j] );
878 $doc->cellValue( $row, $j, $value );
880 $i++;
882 $doc->save();
883 binmode(STDOUT);
884 open $ods_fh, '<', $ods_filepath;
885 $content .= $_ while <$ods_fh>;
886 unlink $ods_filepath;
889 print $input->header(
890 -type => $type,
891 -attachment=> $reportfilename
893 print $content;
895 foreach my $err (@$q_errors, @errors) {
896 print "# ERROR: " . (map {$_ . ": " . $err->{$_}} keys %$err) . "\n";
897 } # here we print all the non-fatal errors at the end. Not super smooth, but better than nothing.
898 exit;
900 $template->param(
901 'sql' => $sql,
902 'execute' => 1,
903 'name' => 'Error exporting report!',
904 'notes' => '',
905 'errors' => $q_errors,
909 elsif ( $phase eq 'Create report from SQL' ) {
911 my ($group, $subgroup);
912 # allow the user to paste in sql
913 if ( $input->param('sql') ) {
914 $group = $input->param('report_group');
915 $subgroup = $input->param('report_subgroup');
916 $template->param(
917 'sql' => scalar $input->param('sql') // '',
918 'reportname' => scalar $input->param('reportname') // '',
919 'notes' => scalar $input->param('notes') // '',
922 $template->param(
923 'create' => 1,
924 'groups_with_subgroups' => groups_with_subgroups($group, $subgroup),
925 'public' => '0',
926 'cache_expiry' => 300,
927 'usecache' => $usecache,
931 elsif ($phase eq 'Create Compound Report'){
932 $template->param( 'savedreports' => get_saved_reports(),
933 'compound' => 1,
937 elsif ($phase eq 'Save Compound'){
938 my $master = $input->param('master');
939 my $subreport = $input->param('subreport');
940 my ($mastertables,$subtables) = create_compound($master,$subreport);
941 $template->param( 'save_compound' => 1,
942 master=>$mastertables,
943 subsql=>$subtables
947 # pass $sth, get back an array of names for the column headers
948 sub header_cell_values {
949 my $sth = shift or return ();
950 return '' unless ($sth->{NAME});
951 return @{$sth->{NAME}};
954 # pass $sth, get back a TMPL_LOOP-able set of names for the column headers
955 sub header_cell_loop {
956 my @headers = map { +{ cell => decode('UTF-8',$_) } } header_cell_values (shift);
957 return \@headers;
960 foreach (1..6) {
961 $template->{VARS}->{'build' . $_} and last;
963 $template->param( 'referer' => $input->referer(),
966 output_html_with_http_headers $input, $cookie, $template->output;
968 sub groups_with_subgroups {
969 my ($group, $subgroup) = @_;
971 my $groups_with_subgroups = get_report_groups();
972 my @g_sg;
973 my @sorted_keys = sort {
974 $groups_with_subgroups->{$a}->{name} cmp $groups_with_subgroups->{$b}->{name}
975 } keys %$groups_with_subgroups;
976 foreach my $g_id (@sorted_keys) {
977 my $v = $groups_with_subgroups->{$g_id};
978 my @subgroups;
979 if (my $sg = $v->{subgroups}) {
980 foreach my $sg_id (sort { $sg->{$a} cmp $sg->{$b} } keys %$sg) {
981 push @subgroups, {
982 id => $sg_id,
983 name => $sg->{$sg_id},
984 selected => ($group && $g_id eq $group && $subgroup && $sg_id eq $subgroup ),
988 push @g_sg, {
989 id => $g_id,
990 name => $v->{name},
991 selected => ($group && $g_id eq $group),
992 subgroups => \@subgroups,
995 return \@g_sg;
998 sub create_non_existing_group_and_subgroup {
999 my ($input, $group, $subgroup) = @_;
1001 if (defined $group and $group ne '') {
1002 my $report_groups = C4::Reports::Guided::get_report_groups;
1003 if (not exists $report_groups->{$group}) {
1004 my $groupdesc = $input->param('groupdesc') // $group;
1005 Koha::AuthorisedValue->new({
1006 category => 'REPORT_GROUP',
1007 authorised_value => $group,
1008 lib => $groupdesc,
1009 })->store;
1011 if (defined $subgroup and $subgroup ne '') {
1012 if (not exists $report_groups->{$group}->{subgroups}->{$subgroup}) {
1013 my $subgroupdesc = $input->param('subgroupdesc') // $subgroup;
1014 Koha::AuthorisedValue->new({
1015 category => 'REPORT_SUBGROUP',
1016 authorised_value => $subgroup,
1017 lib => $subgroupdesc,
1018 lib_opac => $group,
1019 })->store;