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 under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License along
17 # with Koha; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 #use warnings; FIXME - Bug 2505
24 use C4::Reports::Guided;
25 use C4::Auth qw/:DEFAULT get_session/;
29 use C4::Branch; # XXX subfield_is_koha_internal_p
37 Script to control the guided report creation
43 my $phase = $input->param('phase');
45 if ( $phase eq 'Build new' or $phase eq 'Delete Saved' ) {
46 $flagsrequired = 'create_reports';
48 elsif ( $phase eq 'Use saved' ) {
49 $flagsrequired = 'execute_reports';
54 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
56 template_name => "reports/guided_reports_start.tmpl",
60 flagsrequired => { reports => $flagsrequired },
64 my $session = $cookie ? get_session($cookie->value) : undef;
67 if ( $input->param("filter_set") ) {
69 $filter->{$_} = $input->param("filter_$_") foreach qw/date author keyword/;
70 $session->param('report_filter', $filter) if $session;
73 $filter = $session->param('report_filter');
79 $template->param( 'start' => 1 );
82 elsif ( $phase eq 'Build new' ) {
84 $template->param( 'build1' => 1 );
85 $template->param( 'areas' => get_report_areas() );
87 elsif ( $phase eq 'Use saved' ) {
89 # get list of reports and display them
92 'savedreports' => get_saved_reports($filter),
95 while ( my ($k, $v) = each %$filter ) {
96 $template->param( "filter_$k" => $v ) if $v;
101 elsif ( $phase eq 'Delete Saved') {
103 # delete a report from the saved reports list
104 my $id = $input->param('reports');
106 print $input->redirect("/cgi-bin/koha/reports/guided_reports.pl?phase=Use%20saved");
110 elsif ( $phase eq 'Show SQL'){
112 my $id = $input->param('reports');
113 my $sql = get_sql($id);
120 elsif ( $phase eq 'Edit SQL'){
122 my $id = $input->param('reports');
123 my ($sql,$type,$reportname,$notes) = get_saved_report($id);
126 'reportname' => $reportname,
133 elsif ( $phase eq 'Update SQL'){
134 my $id = $input->param('id');
135 my $sql = $input->param('sql');
136 my $reportname = $input->param('reportname');
137 my $notes = $input->param('notes');
139 if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
140 push @errors, {sqlerr => $1};
142 elsif ($sql !~ /^(SELECT)/i) {
143 push @errors, {queryerr => 1};
147 'errors' => \@errors,
152 update_sql( $id, $sql, $reportname, $notes );
154 'save_successful' => 1,
161 elsif ($phase eq 'retrieve results') {
162 my $id = $input->param('id');
163 my ($results,$name,$notes) = format_results($id);
167 'results' => $results,
173 elsif ( $phase eq 'Report on this Area' ) {
175 # they have choosen a new report and the area to report on
178 'area' => $input->param('areas'),
179 'types' => get_report_types(),
183 elsif ( $phase eq 'Choose this type' ) {
185 # they have chosen type and area
186 # get area and type and pass them to the template
187 my $area = $input->param('area');
188 my $type = $input->param('types');
193 columns => get_columns($area,$input),
197 elsif ( $phase eq 'Choose these columns' ) {
199 # we now know type, area, and columns
200 # next step is the constraints
201 my $area = $input->param('area');
202 my $type = $input->param('type');
203 my @columns = $input->param('columns');
204 my $column = join( ',', @columns );
210 definitions => get_from_dictionary($area),
211 criteria => get_criteria($area,$input),
215 elsif ( $phase eq 'Choose these criteria' ) {
216 my $area = $input->param('area');
217 my $type = $input->param('type');
218 my $column = $input->param('column');
219 my @definitions = $input->param('definition');
220 my $definition = join (',',@definitions);
221 my @criteria = $input->param('criteria_column');
223 foreach my $crit (@criteria) {
224 my $value = $input->param( $crit . "_value" );
226 # If value is not defined, then it may be range values
227 if (!defined $value) {
229 my $fromvalue = $input->param( "from_" . $crit . "_value" );
230 my $tovalue = $input->param( "to_" . $crit . "_value" );
232 # If the range values are dates
233 if ($fromvalue =~ C4::Dates->regexp('syspref') && $tovalue =~ C4::Dates->regexp('syspref')) {
234 $fromvalue = C4::Dates->new($fromvalue)->output("iso");
235 $tovalue = C4::Dates->new($tovalue)->output("iso");
238 if ($fromvalue && $tovalue) {
239 $query_criteria .= " AND $crit >= '$fromvalue' AND $crit <= '$tovalue'";
245 if ($value =~ C4::Dates->regexp('syspref')) {
246 $value = C4::Dates->new($value)->output("iso");
248 # don't escape runtime parameters, they'll be at runtime
249 if ($value =~ /<<.*>>/) {
250 $query_criteria .= " AND $crit=$value";
252 $query_criteria .= " AND $crit='$value'";
262 'definition' => $definition,
263 'criteriastring' => $query_criteria,
267 my @columns = split( ',', $column );
270 # build structue for use by tmpl_loop to choose columns to order by
271 # need to do something about the order of the order :)
272 # we also want to use the %columns hash to get the plain english names
273 foreach my $col (@columns) {
274 my %total = (name => $col);
275 my @selects = map {+{ value => $_ }} (qw(sum min max avg count));
276 $total{'select'} = \@selects;
277 push @total_by, \%total;
280 $template->param( 'total_by' => \@total_by );
283 elsif ( $phase eq 'Choose These Operations' ) {
284 my $area = $input->param('area');
285 my $type = $input->param('type');
286 my $column = $input->param('column');
287 my $criteria = $input->param('criteria');
288 my $definition = $input->param('definition');
289 my @total_by = $input->param('total_by');
291 foreach my $total (@total_by) {
292 my $value = $input->param( $total . "_tvalue" );
293 $totals .= "$value($total),";
301 'criteriastring' => $criteria,
303 'definition' => $definition,
307 my @columns = split( ',', $column );
310 # build structue for use by tmpl_loop to choose columns to order by
311 # need to do something about the order of the order :)
312 foreach my $col (@columns) {
313 my %order = (name => $col);
314 my @selects = map {+{ value => $_ }} (qw(asc desc));
315 $order{'select'} = \@selects;
316 push @order_by, \%order;
319 $template->param( 'order_by' => \@order_by );
322 elsif ( $phase eq 'Build Report' ) {
324 # now we have all the info we need and can build the sql
325 my $area = $input->param('area');
326 my $type = $input->param('type');
327 my $column = $input->param('column');
328 my $crit = $input->param('criteria');
329 my $totals = $input->param('totals');
330 my $definition = $input->param('definition');
331 my $query_criteria=$crit;
332 # split the columns up by ,
333 my @columns = split( ',', $column );
334 my @order_by = $input->param('order_by');
337 foreach my $order (@order_by) {
338 my $value = $input->param( $order . "_ovalue" );
339 if ($query_orderby) {
340 $query_orderby .= ",$order $value";
343 $query_orderby = " ORDER BY $order $value";
349 build_query( \@columns, $query_criteria, $query_orderby, $area, $totals, $definition );
357 elsif ( $phase eq 'Save' ) {
358 # Save the report that has just been built
359 my $sql = $input->param('sql');
360 my $type = $input->param('type');
368 elsif ( $phase eq 'Save Report' ) {
369 # save the sql pasted in by a user
370 my $sql = $input->param('sql');
371 my $name = $input->param('reportname');
372 my $type = $input->param('types');
373 my $notes = $input->param('notes');
374 if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
375 push @errors, {sqlerr => $1};
377 elsif ($sql !~ /^(SELECT)/i) {
378 push @errors, {queryerr => 1};
382 'errors' => \@errors,
384 'reportname'=> $name,
390 my $id = save_report( $borrowernumber, $sql, $name, $type, $notes );
392 'save_successful' => 1,
398 elsif ($phase eq 'Run this report'){
399 # execute a saved report
400 my $limit = 20; # page size. # TODO: move to DB or syspref?
402 my $report = $input->param('reports');
403 my @sql_params = $input->param('sql_params');
405 if ($input->param('page')) {
406 $offset = ($input->param('page') - 1) * $limit;
408 my ($sql,$type,$name,$notes) = get_saved_report($report);
410 push @errors, {no_sql_for_id=>$report};
413 # if we have at least 1 parameter, and it's not filled, then don't execute but ask for parameters
414 if ($sql =~ /<</ && !@sql_params) {
415 # split on ??. Each odd (2,4,6,...) entry should be a parameter to fill
416 my @split = split /<<|>>/,$sql;
418 for(my $i=0;$i<($#split/2);$i++) {
419 my ($text,$authorised_value) = split /\|/,$split[$i*2+1];
421 if ($authorised_value) {
422 my $dbh=C4::Context->dbh;
423 my @authorised_values;
425 # builds list, depending on authorised value...
426 if ( $authorised_value eq "branches" ) {
427 my $branches = GetBranchesLoop();
428 foreach my $thisbranch (@$branches) {
429 push @authorised_values, $thisbranch->{value};
430 $authorised_lib{$thisbranch->{value}} = $thisbranch->{branchname};
433 elsif ( $authorised_value eq "itemtypes" ) {
434 my $sth = $dbh->prepare("SELECT itemtype,description FROM itemtypes ORDER BY description");
436 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
437 push @authorised_values, $itemtype;
438 $authorised_lib{$itemtype} = $description;
441 elsif ( $authorised_value eq "cn_source" ) {
442 my $class_sources = GetClassSources();
443 my $default_source = C4::Context->preference("DefaultClassificationSource");
444 foreach my $class_source (sort keys %$class_sources) {
445 next unless $class_sources->{$class_source}->{'used'} or
446 ($class_source eq $default_source);
447 push @authorised_values, $class_source;
448 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
451 elsif ( $authorised_value eq "categorycode" ) {
452 my $sth = $dbh->prepare("SELECT categorycode, description FROM categories ORDER BY description");
454 while ( my ( $categorycode, $description ) = $sth->fetchrow_array ) {
455 push @authorised_values, $categorycode;
456 $authorised_lib{$categorycode} = $description;
459 #---- "true" authorised value
462 my $authorised_values_sth = $dbh->prepare("SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib");
464 $authorised_values_sth->execute( $authorised_value);
466 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
467 push @authorised_values, $value;
468 $authorised_lib{$value} = $lib;
469 # For item location, we show the code and the libelle
470 $authorised_lib{$value} = $lib;
473 $input =CGI::scrolling_list( # FIXME: factor out scrolling_list
474 -name => "sql_params",
475 -values => \@authorised_values,
476 # -default => $value,
477 -labels => \%authorised_lib,
485 $input = "<input type='text' name='sql_params'/>";
487 push @tmpl_parameters, {'entry' => $text, 'input' => $input };
489 $template->param('sql' => $sql,
491 'sql_params' => \@tmpl_parameters,
493 'reports' => $report,
496 # OK, we have parameters, or there are none, we run the report
497 # if there were parameters, replace before running
498 # split on ??. Each odd (2,4,6,...) entry should be a parameter to fill
499 my @split = split /<<|>>/,$sql;
501 for(my $i=0;$i<$#split/2;$i++) {
502 my $quoted = C4::Context->dbh->quote($sql_params[$i]);
503 # if there are special regexp chars, we must \ them
504 $split[$i*2+1] =~ s/(\||\?|\.|\*|\(|\)|\%)/\\$1/g;
505 $sql =~ s/<<$split[$i*2+1]>>/$quoted/;
507 my ($sth, $errors) = execute_query($sql, $offset, $limit);
508 my $total = nb_rows($sql) || 0;
510 die "execute_query failed to return sth for report $report: $sql";
512 my $headref = $sth->{NAME} || [];
513 my @headers = map { +{ cell => $_ } } @$headref;
514 $template->param(header_row => \@headers);
515 while (my $row = $sth->fetchrow_arrayref()) {
516 my @cells = map { +{ cell => $_ } } @$row;
517 push @rows, { cells => \@cells };
521 my $totpages = int($total/$limit) + (($total % $limit) > 0 ? 1 : 0);
522 my $url = "/cgi-bin/koha/reports/guided_reports.pl?reports=$report&phase=Run%20this%20report";
530 'pagination_bar' => pagination_bar($url, $totpages, $input->param('page')),
531 'unlimited_total' => $total,
536 elsif ($phase eq 'Export'){
537 binmode STDOUT, ':utf8';
539 # export results to tab separated text or CSV
540 my $sql = $input->param('sql'); # FIXME: use sql from saved report ID#, not new user-supplied SQL!
541 my $format = $input->param('format');
542 my ($sth, $q_errors) = execute_query($sql);
543 unless ($q_errors and @$q_errors) {
544 print $input->header( -type => 'application/octet-stream',
545 -attachment=>"reportresults.$format"
547 if ($format eq 'tab') {
548 print join("\t", header_cell_values($sth)), "\n";
549 while (my $row = $sth->fetchrow_arrayref()) {
550 print join("\t", @$row), "\n";
553 my $csv = Text::CSV->new({binary => 1});
554 $csv or die "Text::CSV->new({binary => 1}) FAILED: " . Text::CSV->error_diag();
555 if ($csv->combine(header_cell_values($sth))) {
556 print $csv->string(), "\n";
558 push @$q_errors, { combine => 'HEADER ROW: ' . $csv->error_diag() } ;
560 while (my $row = $sth->fetchrow_arrayref()) {
561 if ($csv->combine(@$row)) {
562 print $csv->string(), "\n";
564 push @$q_errors, { combine => $csv->error_diag() } ;
568 foreach my $err (@$q_errors, @errors) {
569 print "# ERROR: " . (map {$_ . ": " . $err->{$_}} keys %$err) . "\n";
570 } # here we print all the non-fatal errors at the end. Not super smooth, but better than nothing.
576 'name' => 'Error exporting report!',
578 'errors' => $q_errors,
582 elsif ($phase eq 'Create report from SQL') {
583 # allow the user to paste in sql
584 if ($input->param('sql')) {
586 'sql' => $input->param('sql'),
587 'reportname' => $input->param('reportname'),
588 'notes' => $input->param('notes'),
591 $template->param('create' => 1);
594 elsif ($phase eq 'Create Compound Report'){
595 $template->param( 'savedreports' => get_saved_reports(),
600 elsif ($phase eq 'Save Compound'){
601 my $master = $input->param('master');
602 my $subreport = $input->param('subreport');
603 my ($mastertables,$subtables) = create_compound($master,$subreport);
604 $template->param( 'save_compound' => 1,
605 master=>$mastertables,
610 # pass $sth, get back an array of names for the column headers
611 sub header_cell_values {
612 my $sth = shift or return ();
613 return @{$sth->{NAME}};
616 # pass $sth, get back a TMPL_LOOP-able set of names for the column headers
617 sub header_cell_loop {
618 my @headers = map { +{ cell => $_ } } header_cell_values (shift);
623 $template->param('build' . $_) and $template->param(buildx => $_) and last;
625 $template->param( 'referer' => $input->referer(),
626 'DHTMLcalendar_dateformat' => C4::Dates->DHTMLcalendar(),
629 output_html_with_http_headers $input, $cookie, $template->output;