Bug 19550: (QA follow-up) Add missing [% USE %]
[koha.git] / reports / guided_reports.pl
blob0989dfdbd19085b0ace02adea79ca7ef5565b0cc
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 Koha::Reports;
29 use C4::Auth qw/:DEFAULT get_session/;
30 use C4::Output;
31 use C4::Debug;
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::BiblioFrameworks;
39 use Koha::Libraries;
40 use Koha::Patron::Categories;
42 =head1 NAME
44 guided_reports.pl
46 =head1 DESCRIPTION
48 Script to control the guided report creation
50 =cut
52 my $input = new CGI;
53 my $usecache = Koha::Caches->get_instance->memcached_cache;
55 my $phase = $input->param('phase') // '';
56 my $flagsrequired;
57 if ( ( $phase eq 'Build new' ) || ( $phase eq 'Create report from SQL' ) || ( $phase eq 'Edit SQL' ) ){
58 $flagsrequired = 'create_reports';
60 elsif ( $phase eq 'Use saved' ) {
61 $flagsrequired = 'execute_reports';
63 elsif ( $phase eq 'Delete Saved' ) {
64 $flagsrequired = 'delete_reports';
66 else {
67 $flagsrequired = '*';
70 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
72 template_name => "reports/guided_reports_start.tt",
73 query => $input,
74 type => "intranet",
75 authnotrequired => 0,
76 flagsrequired => { reports => $flagsrequired },
77 debug => 1,
80 my $session = $cookie ? get_session($cookie->value) : undef;
82 my $filter;
83 if ( $input->param("filter_set") or $input->param('clear_filters') ) {
84 $filter = {};
85 $filter->{$_} = $input->param("filter_$_") foreach qw/date author keyword group subgroup/;
86 $session->param('report_filter', $filter) if $session;
87 $template->param( 'filter_set' => 1 );
89 elsif ($session and not $input->param('clear_filters')) {
90 $filter = $session->param('report_filter');
93 my $op = $input->param('op') || q||;
95 my @errors = ();
96 if ( !$phase ) {
97 $template->param( 'start' => 1 );
98 # show welcome page
100 elsif ( $phase eq 'Build new' ) {
101 # build a new report
102 $template->param( 'build1' => 1 );
103 $template->param(
104 'areas' => get_report_areas(),
105 'usecache' => $usecache,
106 'cache_expiry' => 300,
107 'public' => '0',
109 } elsif ( $phase eq 'Use saved' ) {
111 if ( $op eq 'convert' ) {
112 my $report_id = $input->param('report_id');
113 my $report = Koha::Reports->find($report_id);
114 if ($report) {
115 my $updated_sql = C4::Reports::Guided::convert_sql( $report->savedsql );
116 C4::Reports::Guided::update_sql(
117 $report_id,
119 sql => $updated_sql,
120 name => $report->report_name,
121 group => $report->report_group,
122 subgroup => $report->report_subgroup,
123 notes => $report->notes,
124 public => $report->public,
125 cache_expiry => $report->cache_expiry,
128 $template->param( report_converted => $report->report_name );
132 # use a saved report
133 # get list of reports and display them
134 my $group = $input->param('group');
135 my $subgroup = $input->param('subgroup');
136 $filter->{group} = $group;
137 $filter->{subgroup} = $subgroup;
138 my $reports = get_saved_reports($filter);
139 my $has_obsolete_reports;
140 for my $report ( @$reports ) {
141 $report->{results} = C4::Reports::Guided::get_results( $report->{id} );
142 if ( $report->{savedsql} =~ m|biblioitems| and $report->{savedsql} =~ m|marcxml| ) {
143 $report->{seems_obsolete} = 1;
144 $has_obsolete_reports++;
147 $template->param(
148 'saved1' => 1,
149 'savedreports' => $reports,
150 'usecache' => $usecache,
151 'groups_with_subgroups' => groups_with_subgroups( $group, $subgroup ),
152 filters => $filter,
153 has_obsolete_reports => $has_obsolete_reports,
157 elsif ( $phase eq 'Delete Multiple') {
158 my @ids = $input->multi_param('ids');
159 delete_report( @ids );
160 print $input->redirect("/cgi-bin/koha/reports/guided_reports.pl?phase=Use%20saved");
161 exit;
164 elsif ( $phase eq 'Delete Saved') {
166 # delete a report from the saved reports list
167 my $ids = $input->param('reports');
168 delete_report($ids);
169 print $input->redirect("/cgi-bin/koha/reports/guided_reports.pl?phase=Use%20saved");
170 exit;
173 elsif ( $phase eq 'Show SQL'){
175 my $id = $input->param('reports');
176 my $report = Koha::Reports->find($id);
177 $template->param(
178 'id' => $id,
179 'reportname' => $report->report_name,
180 'notes' => $report->notes,
181 'sql' => $report->savedsql,
182 'showsql' => 1,
186 elsif ( $phase eq 'Edit SQL'){
187 my $id = $input->param('reports');
188 my $report = Koha::Reports->find($id);
189 my $group = $report->report_group;
190 my $subgroup = $report->report_subgroup;
191 $template->param(
192 'sql' => $report->savedsql,
193 'reportname' => $report->report_name,
194 'groups_with_subgroups' => groups_with_subgroups($group, $subgroup),
195 'notes' => $report->notes,
196 'id' => $id,
197 'cache_expiry' => $report->cache_expiry,
198 'public' => $report->public,
199 'usecache' => $usecache,
200 'editsql' => 1,
204 elsif ( $phase eq 'Update SQL'){
205 my $id = $input->param('id');
206 my $sql = $input->param('sql');
207 my $reportname = $input->param('reportname');
208 my $group = $input->param('group');
209 my $subgroup = $input->param('subgroup');
210 my $notes = $input->param('notes');
211 my $cache_expiry = $input->param('cache_expiry');
212 my $cache_expiry_units = $input->param('cache_expiry_units');
213 my $public = $input->param('public');
214 my $save_anyway = $input->param('save_anyway');
216 my @errors;
218 # if we have the units, then we came from creating a report from SQL and thus need to handle converting units
219 if( $cache_expiry_units ){
220 if( $cache_expiry_units eq "minutes" ){
221 $cache_expiry *= 60;
222 } elsif( $cache_expiry_units eq "hours" ){
223 $cache_expiry *= 3600; # 60 * 60
224 } elsif( $cache_expiry_units eq "days" ){
225 $cache_expiry *= 86400; # 60 * 60 * 24
228 # 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
229 if( $cache_expiry >= 2592000 ){
230 push @errors, {cache_expiry => $cache_expiry};
233 create_non_existing_group_and_subgroup($input, $group, $subgroup);
235 if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
236 push @errors, {sqlerr => $1};
238 elsif ($sql !~ /^(SELECT)/i) {
239 push @errors, {queryerr => "No SELECT"};
242 if (@errors) {
243 $template->param(
244 'errors' => \@errors,
245 'sql' => $sql,
247 } else {
249 # Check defined SQL parameters for authorised value validity
250 my $problematic_authvals = ValidateSQLParameters($sql);
252 if ( scalar @$problematic_authvals > 0 && not $save_anyway ) {
253 # There's at least one problematic parameter, report to the
254 # GUI and provide all user input for further actions
255 $template->param(
256 'id' => $id,
257 'sql' => $sql,
258 'reportname' => $reportname,
259 'group' => $group,
260 'subgroup' => $subgroup,
261 'notes' => $notes,
262 'public' => $public,
263 'problematic_authvals' => $problematic_authvals,
264 'warn_authval_problem' => 1,
265 'phase_update' => 1
268 } else {
269 # No params problem found or asked to save anyway
270 update_sql( $id, {
271 sql => $sql,
272 name => $reportname,
273 group => $group,
274 subgroup => $subgroup,
275 notes => $notes,
276 public => $public,
277 cache_expiry => $cache_expiry,
278 } );
279 $template->param(
280 'save_successful' => 1,
281 'reportname' => $reportname,
282 'id' => $id,
283 'editsql' => 1,
284 'sql' => $sql,
285 'groups_with_subgroups' => groups_with_subgroups($group, $subgroup),
286 'notes' => $notes,
287 'cache_expiry' => $cache_expiry,
288 'public' => $public,
289 'usecache' => $usecache,
291 logaction( "REPORTS", "MODIFY", $id, "$reportname | $sql" ) if C4::Context->preference("ReportsLog");
293 if ( $usecache ) {
294 $template->param(
295 cache_expiry => $cache_expiry,
296 cache_expiry_units => $cache_expiry_units,
302 elsif ($phase eq 'retrieve results') {
303 my $id = $input->param('id');
304 my $result = format_results( $id );
305 $template->param(
306 report_name => $result->{report_name},
307 notes => $result->{notes},
308 saved_results => $result->{results},
309 date_run => $result->{date_run},
313 elsif ( $phase eq 'Report on this Area' ) {
314 my $cache_expiry_units = $input->param('cache_expiry_units'),
315 my $cache_expiry = $input->param('cache_expiry');
317 # we need to handle converting units
318 if( $cache_expiry_units eq "minutes" ){
319 $cache_expiry *= 60;
320 } elsif( $cache_expiry_units eq "hours" ){
321 $cache_expiry *= 3600; # 60 * 60
322 } elsif( $cache_expiry_units eq "days" ){
323 $cache_expiry *= 86400; # 60 * 60 * 24
325 # 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
326 if( $cache_expiry >= 2592000 ){ # oops, over the limit of 30 days
327 # report error to user
328 $template->param(
329 'cache_error' => 1,
330 'build1' => 1,
331 'areas' => get_report_areas(),
332 'cache_expiry' => $cache_expiry,
333 'usecache' => $usecache,
334 'public' => scalar $input->param('public'),
336 } else {
337 # they have choosen a new report and the area to report on
338 $template->param(
339 'build2' => 1,
340 'area' => scalar $input->param('area'),
341 'types' => get_report_types(),
342 'cache_expiry' => $cache_expiry,
343 'public' => scalar $input->param('public'),
348 elsif ( $phase eq 'Choose this type' ) {
349 # they have chosen type and area
350 # get area and type and pass them to the template
351 my $area = $input->param('area');
352 my $type = $input->param('types');
353 $template->param(
354 'build3' => 1,
355 'area' => $area,
356 'type' => $type,
357 columns => get_columns($area,$input),
358 'cache_expiry' => scalar $input->param('cache_expiry'),
359 'public' => scalar $input->param('public'),
363 elsif ( $phase eq 'Choose these columns' ) {
364 # we now know type, area, and columns
365 # next step is the constraints
366 my $area = $input->param('area');
367 my $type = $input->param('type');
368 my @columns = $input->multi_param('columns');
369 my $column = join( ',', @columns );
371 $template->param(
372 'build4' => 1,
373 'area' => $area,
374 'type' => $type,
375 'column' => $column,
376 definitions => get_from_dictionary($area),
377 criteria => get_criteria($area,$input),
378 'public' => scalar $input->param('public'),
380 if ( $usecache ) {
381 $template->param(
382 cache_expiry => scalar $input->param('cache_expiry'),
383 cache_expiry_units => scalar $input->param('cache_expiry_units'),
389 elsif ( $phase eq 'Choose these criteria' ) {
390 my $area = $input->param('area');
391 my $type = $input->param('type');
392 my $column = $input->param('column');
393 my @definitions = $input->multi_param('definition');
394 my $definition = join (',',@definitions);
395 my @criteria = $input->multi_param('criteria_column');
396 my $query_criteria;
397 foreach my $crit (@criteria) {
398 my $value = $input->param( $crit . "_value" );
400 # If value is not defined, then it may be range values
401 if (!defined $value) {
403 my $fromvalue = $input->param( "from_" . $crit . "_value" );
404 my $tovalue = $input->param( "to_" . $crit . "_value" );
406 # If the range values are dates
407 my $fromvalue_dt;
408 $fromvalue_dt = eval { dt_from_string( $fromvalue ); } if ( $fromvalue );
409 my $tovalue_dt;
410 $tovalue_dt = eval { dt_from_string( $tovalue ); } if ($tovalue);
411 if ( $fromvalue_dt && $tovalue_dt ) {
412 $fromvalue = output_pref( { dt => dt_from_string( $fromvalue_dt ), dateonly => 1, dateformat => 'iso' } );
413 $tovalue = output_pref( { dt => dt_from_string( $tovalue_dt ), dateonly => 1, dateformat => 'iso' } );
416 if ($fromvalue && $tovalue) {
417 $query_criteria .= " AND $crit >= '$fromvalue' AND $crit <= '$tovalue'";
420 } else {
422 # If value is a date
423 my $value_dt;
424 $value_dt = eval { dt_from_string( $value ); } if ( $value );
425 if ( $value_dt ) {
426 $value = output_pref( { dt => dt_from_string( $value_dt ), dateonly => 1, dateformat => 'iso' } );
428 # don't escape runtime parameters, they'll be at runtime
429 if ($value =~ /<<.*>>/) {
430 $query_criteria .= " AND $crit=$value";
431 } else {
432 $query_criteria .= " AND $crit='$value'";
436 $template->param(
437 'build5' => 1,
438 'area' => $area,
439 'type' => $type,
440 'column' => $column,
441 'definition' => $definition,
442 'criteriastring' => $query_criteria,
443 'public' => scalar $input->param('public'),
445 if ( $usecache ) {
446 $template->param(
447 cache_expiry => scalar $input->param('cache_expiry'),
448 cache_expiry_units => scalar $input->param('cache_expiry_units'),
452 # get columns
453 my @columns = split( ',', $column );
454 my @total_by;
456 # build structue for use by tmpl_loop to choose columns to order by
457 # need to do something about the order of the order :)
458 # we also want to use the %columns hash to get the plain english names
459 foreach my $col (@columns) {
460 my %total = (name => $col);
461 my @selects = map {+{ value => $_ }} (qw(sum min max avg count));
462 $total{'select'} = \@selects;
463 push @total_by, \%total;
466 $template->param( 'total_by' => \@total_by );
469 elsif ( $phase eq 'Choose these operations' ) {
470 my $area = $input->param('area');
471 my $type = $input->param('type');
472 my $column = $input->param('column');
473 my $criteria = $input->param('criteria');
474 my $definition = $input->param('definition');
475 my @total_by = $input->multi_param('total_by');
476 my $totals;
477 foreach my $total (@total_by) {
478 my $value = $input->param( $total . "_tvalue" );
479 $totals .= "$value($total),";
482 $template->param(
483 'build6' => 1,
484 'area' => $area,
485 'type' => $type,
486 'column' => $column,
487 'criteriastring' => $criteria,
488 'totals' => $totals,
489 'definition' => $definition,
490 'cache_expiry' => scalar $input->param('cache_expiry'),
491 'public' => scalar $input->param('public'),
494 # get columns
495 my @columns = split( ',', $column );
496 my @order_by;
498 # build structue for use by tmpl_loop to choose columns to order by
499 # need to do something about the order of the order :)
500 foreach my $col (@columns) {
501 my %order = (name => $col);
502 my @selects = map {+{ value => $_ }} (qw(asc desc));
503 $order{'select'} = \@selects;
504 push @order_by, \%order;
507 $template->param( 'order_by' => \@order_by );
510 elsif ( $phase eq 'Build report' ) {
512 # now we have all the info we need and can build the sql
513 my $area = $input->param('area');
514 my $type = $input->param('type');
515 my $column = $input->param('column');
516 my $crit = $input->param('criteria');
517 my $totals = $input->param('totals');
518 my $definition = $input->param('definition');
519 my $query_criteria=$crit;
520 # split the columns up by ,
521 my @columns = split( ',', $column );
522 my @order_by = $input->multi_param('order_by');
524 my $query_orderby;
525 foreach my $order (@order_by) {
526 my $value = $input->param( $order . "_ovalue" );
527 if ($query_orderby) {
528 $query_orderby .= ",$order $value";
530 else {
531 $query_orderby = " ORDER BY $order $value";
535 # get the sql
536 my $sql =
537 build_query( \@columns, $query_criteria, $query_orderby, $area, $totals, $definition );
538 $template->param(
539 'showreport' => 1,
540 'area' => $area,
541 'sql' => $sql,
542 'type' => $type,
543 'cache_expiry' => scalar $input->param('cache_expiry'),
544 'public' => scalar $input->param('public'),
548 elsif ( $phase eq 'Save' ) {
549 # Save the report that has just been built
550 my $area = $input->param('area');
551 my $sql = $input->param('sql');
552 my $type = $input->param('type');
553 $template->param(
554 'save' => 1,
555 'area' => $area,
556 'sql' => $sql,
557 'type' => $type,
558 'cache_expiry' => scalar $input->param('cache_expiry'),
559 'public' => scalar $input->param('public'),
560 'groups_with_subgroups' => groups_with_subgroups($area), # in case we have a report group that matches area
564 elsif ( $phase eq 'Save Report' ) {
565 # save the sql pasted in by a user
566 my $area = $input->param('area');
567 my $group = $input->param('group');
568 my $subgroup = $input->param('subgroup');
569 my $sql = $input->param('sql');
570 my $name = $input->param('reportname');
571 my $type = $input->param('types');
572 my $notes = $input->param('notes');
573 my $cache_expiry = $input->param('cache_expiry');
574 my $cache_expiry_units = $input->param('cache_expiry_units');
575 my $public = $input->param('public');
576 my $save_anyway = $input->param('save_anyway');
579 # if we have the units, then we came from creating a report from SQL and thus need to handle converting units
580 if( $cache_expiry_units ){
581 if( $cache_expiry_units eq "minutes" ){
582 $cache_expiry *= 60;
583 } elsif( $cache_expiry_units eq "hours" ){
584 $cache_expiry *= 3600; # 60 * 60
585 } elsif( $cache_expiry_units eq "days" ){
586 $cache_expiry *= 86400; # 60 * 60 * 24
589 # 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
590 if( $cache_expiry && $cache_expiry >= 2592000 ){
591 push @errors, {cache_expiry => $cache_expiry};
594 create_non_existing_group_and_subgroup($input, $group, $subgroup);
596 ## FIXME this is AFTER entering a name to save the report under
597 if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
598 push @errors, {sqlerr => $1};
600 elsif ($sql !~ /^(SELECT)/i) {
601 push @errors, {queryerr => "No SELECT"};
604 if (@errors) {
605 $template->param(
606 'errors' => \@errors,
607 'sql' => $sql,
608 'reportname'=> $name,
609 'type' => $type,
610 'notes' => $notes,
611 'cache_expiry' => $cache_expiry,
612 'public' => $public,
614 } else {
615 # Check defined SQL parameters for authorised value validity
616 my $problematic_authvals = ValidateSQLParameters($sql);
618 if ( scalar @$problematic_authvals > 0 && not $save_anyway ) {
619 # There's at least one problematic parameter, report to the
620 # GUI and provide all user input for further actions
621 $template->param(
622 'area' => $area,
623 'group' => $group,
624 'subgroup' => $subgroup,
625 'sql' => $sql,
626 'reportname' => $name,
627 'type' => $type,
628 'notes' => $notes,
629 'public' => $public,
630 'problematic_authvals' => $problematic_authvals,
631 'warn_authval_problem' => 1,
632 'phase_save' => 1
634 if ( $usecache ) {
635 $template->param(
636 cache_expiry => $cache_expiry,
637 cache_expiry_units => $cache_expiry_units,
640 } else {
641 # No params problem found or asked to save anyway
642 my $id = save_report( {
643 borrowernumber => $borrowernumber,
644 sql => $sql,
645 name => $name,
646 area => $area,
647 group => $group,
648 subgroup => $subgroup,
649 type => $type,
650 notes => $notes,
651 cache_expiry => $cache_expiry,
652 public => $public,
653 } );
654 logaction( "REPORTS", "ADD", $id, "$name | $sql" ) if C4::Context->preference("ReportsLog");
655 $template->param(
656 'save_successful' => 1,
657 'reportname' => $name,
658 'id' => $id,
659 'editsql' => 1,
660 'sql' => $sql,
661 'groups_with_subgroups' => groups_with_subgroups($group, $subgroup),
662 'notes' => $notes,
663 'cache_expiry' => $cache_expiry,
664 'public' => $public,
665 'usecache' => $usecache,
671 elsif ($phase eq 'Run this report'){
672 # execute a saved report
673 my $limit = $input->param('limit') || 20;
674 my $offset = 0;
675 my $report_id = $input->param('reports');
676 my @sql_params = $input->multi_param('sql_params');
677 my @param_names = $input->multi_param('param_name');
679 # offset algorithm
680 if ($input->param('page')) {
681 $offset = ($input->param('page') - 1) * $limit;
684 $template->param(
685 'limit' => $limit,
686 'report_id' => $report_id,
689 my ( $sql, $original_sql, $type, $name, $notes );
690 if (my $report = Koha::Reports->find($report_id)) {
691 $sql = $original_sql = $report->savedsql;
692 $name = $report->report_name;
693 $notes = $report->notes;
695 my @rows = ();
696 # if we have at least 1 parameter, and it's not filled, then don't execute but ask for parameters
697 if ($sql =~ /<</ && !@sql_params) {
698 # split on ??. Each odd (2,4,6,...) entry should be a parameter to fill
699 my @split = split /<<|>>/,$sql;
700 my @tmpl_parameters;
701 my @authval_errors;
702 my %uniq_params;
703 for(my $i=0;$i<($#split/2);$i++) {
704 my ($text,$authorised_value) = split /\|/,$split[$i*2+1];
705 my $sep = $authorised_value ? "|" : "";
706 if( defined $uniq_params{$text.$sep.$authorised_value} ){
707 next;
708 } else { $uniq_params{$text.$sep.$authorised_value} = "$i"; }
709 my $input;
710 my $labelid;
711 if ( not defined $authorised_value ) {
712 # no authorised value input, provide a text box
713 $input = "text";
714 } elsif ( $authorised_value eq "date" ) {
715 # require a date, provide a date picker
716 $input = 'date';
717 } else {
718 # defined $authorised_value, and not 'date'
719 my $dbh=C4::Context->dbh;
720 my @authorised_values;
721 my %authorised_lib;
722 # builds list, depending on authorised value...
723 if ( $authorised_value eq "branches" ) {
724 my $libraries = Koha::Libraries->search( {}, { order_by => ['branchname'] } );
725 while ( my $library = $libraries->next ) {
726 push @authorised_values, $library->branchcode;
727 $authorised_lib{$library->branchcode} = $library->branchname;
730 elsif ( $authorised_value eq "itemtypes" ) {
731 my $sth = $dbh->prepare("SELECT itemtype,description FROM itemtypes ORDER BY description");
732 $sth->execute;
733 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
734 push @authorised_values, $itemtype;
735 $authorised_lib{$itemtype} = $description;
738 elsif ( $authorised_value eq "biblio_framework" ) {
739 my @frameworks = Koha::BiblioFrameworks->search({}, { order_by => ['frameworktext'] });
740 my $default_source = '';
741 push @authorised_values,$default_source;
742 $authorised_lib{$default_source} = 'Default';
743 foreach my $framework (@frameworks) {
744 push @authorised_values, $framework->frameworkcode;
745 $authorised_lib{$framework->frameworkcode} = $framework->frameworktext;
748 elsif ( $authorised_value eq "cn_source" ) {
749 my $class_sources = GetClassSources();
750 my $default_source = C4::Context->preference("DefaultClassificationSource");
751 foreach my $class_source (sort keys %$class_sources) {
752 next unless $class_sources->{$class_source}->{'used'} or
753 ($class_source eq $default_source);
754 push @authorised_values, $class_source;
755 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
758 elsif ( $authorised_value eq "categorycode" ) {
759 my @patron_categories = Koha::Patron::Categories->search({}, { order_by => ['description']});
760 %authorised_lib = map { $_->categorycode => $_->description } @patron_categories;
761 push @authorised_values, $_->categorycode for @patron_categories;
763 else {
764 if ( Koha::AuthorisedValues->search({ category => $authorised_value })->count ) {
765 my $query = '
766 SELECT authorised_value,lib
767 FROM authorised_values
768 WHERE category=?
769 ORDER BY lib
771 my $authorised_values_sth = $dbh->prepare($query);
772 $authorised_values_sth->execute( $authorised_value);
774 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
775 push @authorised_values, $value;
776 $authorised_lib{$value} = $lib;
777 # For item location, we show the code and the libelle
778 $authorised_lib{$value} = $lib;
780 } else {
781 # not exists $authorised_value_categories{$authorised_value})
782 push @authval_errors, {'entry' => $text,
783 'auth_val' => $authorised_value };
784 # tell the template there's an error
785 $template->param( auth_val_error => 1 );
786 # skip scrolling list creation and params push
787 next;
790 $labelid = $text;
791 $labelid =~ s/\W//g;
792 $input = {
793 name => "sql_params",
794 id => "sql_params_".$labelid,
795 values => \@authorised_values,
796 labels => \%authorised_lib,
800 push @tmpl_parameters, {'entry' => $text, 'input' => $input, 'labelid' => $labelid, 'name' => $text.$sep.$authorised_value };
802 $template->param('sql' => $sql,
803 'name' => $name,
804 'sql_params' => \@tmpl_parameters,
805 'auth_val_errors' => \@authval_errors,
806 'enter_params' => 1,
807 'reports' => $report_id,
809 } else {
810 my $sql = get_prepped_report( $sql, \@param_names, \@sql_params);
811 my ( $sth, $errors ) = execute_query( $sql, $offset, $limit, undef, $report_id );
812 my $total = nb_rows($sql) || 0;
813 unless ($sth) {
814 die "execute_query failed to return sth for report $report_id: $sql";
815 } else {
816 my $headers = header_cell_loop($sth);
817 $template->param(header_row => $headers);
818 while (my $row = $sth->fetchrow_arrayref()) {
819 my @cells = map { +{ cell => $_ } } @$row;
820 push @rows, { cells => \@cells };
824 my $totpages = int($total/$limit) + (($total % $limit) > 0 ? 1 : 0);
825 my $url = "/cgi-bin/koha/reports/guided_reports.pl?reports=$report_id&amp;phase=Run%20this%20report&amp;limit=$limit";
826 if (@sql_params) {
827 $url = join('&amp;sql_params=', $url, map { URI::Escape::uri_escape_utf8($_) } @sql_params);
829 $template->param(
830 'results' => \@rows,
831 'sql' => $sql,
832 original_sql => $original_sql,
833 'id' => $report_id,
834 'execute' => 1,
835 'name' => $name,
836 'notes' => $notes,
837 'errors' => defined($errors) ? [ $errors ] : undef,
838 'pagination_bar' => pagination_bar($url, $totpages, scalar $input->param('page')),
839 'unlimited_total' => $total,
840 'sql_params' => \@sql_params,
841 'param_names' => \@param_names,
845 else {
846 push @errors, { no_sql_for_id => $report_id };
850 elsif ($phase eq 'Export'){
852 # export results to tab separated text or CSV
853 my $report_id = $input->param('report_id');
854 my $report = Koha::Reports->find($report_id);
855 my $sql = $report->savedsql;
856 my @param_names = $input->multi_param('param_name');
857 my @sql_params = $input->multi_param('sql_params');
858 my $format = $input->param('format');
859 my $reportname = $input->param('reportname');
860 my $reportfilename = $reportname ? "$reportname-reportresults.$format" : "reportresults.$format" ;
862 $sql = get_prepped_report( $sql, \@param_names, \@sql_params );
863 my ($sth, $q_errors) = execute_query($sql);
864 unless ($q_errors and @$q_errors) {
865 my ( $type, $content );
866 if ($format eq 'tab') {
867 $type = 'application/octet-stream';
868 $content .= join("\t", header_cell_values($sth)) . "\n";
869 $content = Encode::decode('UTF-8', $content);
870 while (my $row = $sth->fetchrow_arrayref()) {
871 $content .= join("\t", @$row) . "\n";
873 } else {
874 my $delimiter = C4::Context->preference('delimiter') || ',';
875 if ( $format eq 'csv' ) {
876 $delimiter = "\t" if $delimiter eq 'tabulation';
877 $type = 'application/csv';
878 my $csv = Text::CSV::Encoded->new({ encoding_out => 'UTF-8', sep_char => $delimiter});
879 $csv or die "Text::CSV::Encoded->new({binary => 1}) FAILED: " . Text::CSV::Encoded->error_diag();
880 if ($csv->combine(header_cell_values($sth))) {
881 $content .= Encode::decode('UTF-8', $csv->string()) . "\n";
882 } else {
883 push @$q_errors, { combine => 'HEADER ROW: ' . $csv->error_diag() } ;
885 while (my $row = $sth->fetchrow_arrayref()) {
886 if ($csv->combine(@$row)) {
887 $content .= $csv->string() . "\n";
888 } else {
889 push @$q_errors, { combine => $csv->error_diag() } ;
893 elsif ( $format eq 'ods' ) {
894 $type = 'application/vnd.oasis.opendocument.spreadsheet';
895 my $ods_fh = File::Temp->new( UNLINK => 0 );
896 my $ods_filepath = $ods_fh->filename;
898 use OpenOffice::OODoc;
899 my $tmpdir = dirname $ods_filepath;
900 odfWorkingDirectory( $tmpdir );
901 my $container = odfContainer( $ods_filepath, create => 'spreadsheet' );
902 my $doc = odfDocument (
903 container => $container,
904 part => 'content'
906 my $table = $doc->getTable(0);
907 my @headers = header_cell_values( $sth );
908 my $rows = $sth->fetchall_arrayref();
909 my ( $nb_rows, $nb_cols ) = ( 0, 0 );
910 $nb_rows = @$rows;
911 $nb_cols = @headers;
912 $doc->expandTable( $table, $nb_rows + 1, $nb_cols );
914 my $row = $doc->getRow( $table, 0 );
915 my $j = 0;
916 for my $header ( @headers ) {
917 $doc->cellValue( $row, $j, $header );
918 $j++;
920 my $i = 1;
921 for ( @$rows ) {
922 $row = $doc->getRow( $table, $i );
923 for ( my $j = 0 ; $j < $nb_cols ; $j++ ) {
924 my $value = Encode::encode( 'UTF8', $rows->[$i - 1][$j] );
925 $doc->cellValue( $row, $j, $value );
927 $i++;
929 $doc->save();
930 binmode(STDOUT);
931 open $ods_fh, '<', $ods_filepath;
932 $content .= $_ while <$ods_fh>;
933 unlink $ods_filepath;
936 print $input->header(
937 -type => $type,
938 -attachment=> $reportfilename
940 print $content;
942 foreach my $err (@$q_errors, @errors) {
943 print "# ERROR: " . (map {$_ . ": " . $err->{$_}} keys %$err) . "\n";
944 } # here we print all the non-fatal errors at the end. Not super smooth, but better than nothing.
945 exit;
947 $template->param(
948 'sql' => $sql,
949 'execute' => 1,
950 'name' => 'Error exporting report!',
951 'notes' => '',
952 'errors' => $q_errors,
956 elsif ( $phase eq 'Create report from SQL' ) {
958 my ($group, $subgroup);
959 # allow the user to paste in sql
960 if ( $input->param('sql') ) {
961 $group = $input->param('report_group');
962 $subgroup = $input->param('report_subgroup');
963 $template->param(
964 'sql' => scalar $input->param('sql') // '',
965 'reportname' => scalar $input->param('reportname') // '',
966 'notes' => scalar $input->param('notes') // '',
969 $template->param(
970 'create' => 1,
971 'groups_with_subgroups' => groups_with_subgroups($group, $subgroup),
972 'public' => '0',
973 'cache_expiry' => 300,
974 'usecache' => $usecache,
978 # pass $sth, get back an array of names for the column headers
979 sub header_cell_values {
980 my $sth = shift or return ();
981 return '' unless ($sth->{NAME});
982 return @{$sth->{NAME}};
985 # pass $sth, get back a TMPL_LOOP-able set of names for the column headers
986 sub header_cell_loop {
987 my @headers = map { +{ cell => decode('UTF-8',$_) } } header_cell_values (shift);
988 return \@headers;
991 foreach (1..6) {
992 $template->{VARS}->{'build' . $_} and last;
994 $template->param( 'referer' => $input->referer(),
997 output_html_with_http_headers $input, $cookie, $template->output;
999 sub groups_with_subgroups {
1000 my ($group, $subgroup) = @_;
1002 my $groups_with_subgroups = get_report_groups();
1003 my @g_sg;
1004 my @sorted_keys = sort {
1005 $groups_with_subgroups->{$a}->{name} cmp $groups_with_subgroups->{$b}->{name}
1006 } keys %$groups_with_subgroups;
1007 foreach my $g_id (@sorted_keys) {
1008 my $v = $groups_with_subgroups->{$g_id};
1009 my @subgroups;
1010 if (my $sg = $v->{subgroups}) {
1011 foreach my $sg_id (sort { $sg->{$a} cmp $sg->{$b} } keys %$sg) {
1012 push @subgroups, {
1013 id => $sg_id,
1014 name => $sg->{$sg_id},
1015 selected => ($group && $g_id eq $group && $subgroup && $sg_id eq $subgroup ),
1019 push @g_sg, {
1020 id => $g_id,
1021 name => $v->{name},
1022 selected => ($group && $g_id eq $group),
1023 subgroups => \@subgroups,
1026 return \@g_sg;
1029 sub create_non_existing_group_and_subgroup {
1030 my ($input, $group, $subgroup) = @_;
1032 if (defined $group and $group ne '') {
1033 my $report_groups = C4::Reports::Guided::get_report_groups;
1034 if (not exists $report_groups->{$group}) {
1035 my $groupdesc = $input->param('groupdesc') // $group;
1036 Koha::AuthorisedValue->new({
1037 category => 'REPORT_GROUP',
1038 authorised_value => $group,
1039 lib => $groupdesc,
1040 })->store;
1042 if (defined $subgroup and $subgroup ne '') {
1043 if (not exists $report_groups->{$group}->{subgroups}->{$subgroup}) {
1044 my $subgroupdesc = $input->param('subgroupdesc') // $subgroup;
1045 Koha::AuthorisedValue->new({
1046 category => 'REPORT_SUBGROUP',
1047 authorised_value => $subgroup,
1048 lib => $subgroupdesc,
1049 lib_opac => $group,
1050 })->store;
1056 # pass $sth and sql_params, get back an executable query
1057 sub get_prepped_report {
1058 my ($sql, $param_names, $sql_params ) = @_;
1059 my %lookup;
1060 @lookup{@$param_names} = @$sql_params;
1061 my @split = split /<<|>>/,$sql;
1062 my @tmpl_parameters;
1063 for(my $i=0;$i<$#split/2;$i++) {
1064 my $quoted = @$param_names ? $lookup{ $split[$i*2+1] } : @$sql_params[$i];
1065 # if there are special regexp chars, we must \ them
1066 $split[$i*2+1] =~ s/(\||\?|\.|\*|\(|\)|\%)/\\$1/g;
1067 if ($split[$i*2+1] =~ /\|\s*date\s*$/) {
1068 $quoted = output_pref({ dt => dt_from_string($quoted), dateformat => 'iso', dateonly => 1 }) if $quoted;
1070 $quoted = C4::Context->dbh->quote($quoted);
1071 $sql =~ s/<<$split[$i*2+1]>>/$quoted/;
1073 return $sql;