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;
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' ) {
46 $flagsrequired = 'create_report';
48 elsif ( $phase eq 'Use saved' ) {
49 $flagsrequired = 'execute_report';
54 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
56 template_name => "reports/guided_reports_start.tmpl",
60 flagsrequired => { reports => $flagsrequired },
67 $template->param( 'start' => 1 );
70 elsif ( $phase eq 'Build new' ) {
72 $template->param( 'build1' => 1 );
73 $template->param( 'areas' => get_report_areas() );
75 elsif ( $phase eq 'Use saved' ) {
77 # get list of reports and display them
78 $template->param( 'saved1' => 1 );
79 $template->param( 'savedreports' => get_saved_reports() );
82 elsif ( $phase eq 'Delete Saved') {
84 # delete a report from the saved reports list
85 my $id = $input->param('reports');
87 print $input->redirect("/cgi-bin/koha/reports/guided_reports.pl?phase=Use%20saved");
91 elsif ( $phase eq 'Show SQL'){
93 my $id = $input->param('reports');
94 my $sql = get_sql($id);
101 elsif ( $phase eq 'Edit SQL'){
103 my $id = $input->param('reports');
104 my ($sql,$type,$reportname,$notes) = get_saved_report($id);
107 'reportname' => $reportname,
114 elsif ( $phase eq 'Update SQL'){
115 my $id = $input->param('id');
116 my $sql = $input->param('sql');
117 my $reportname = $input->param('reportname');
118 my $notes = $input->param('notes');
120 if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
121 push @errors, {sqlerr => $1};
123 elsif ($sql !~ /^(SELECT)/i) {
124 push @errors, {queryerr => 1};
128 'errors' => \@errors,
133 update_sql( $id, $sql, $reportname, $notes );
135 'save_successful' => 1,
141 elsif ($phase eq 'retrieve results') {
142 my $id = $input->param('id');
143 my ($results,$name,$notes) = format_results($id);
147 'results' => $results,
153 elsif ( $phase eq 'Report on this Area' ) {
155 # they have choosen a new report and the area to report on
158 'area' => $input->param('areas'),
159 'types' => get_report_types(),
163 elsif ( $phase eq 'Choose this type' ) {
165 # they have chosen type and area
166 # get area and type and pass them to the template
167 my $area = $input->param('area');
168 my $type = $input->param('types');
173 columns => get_columns($area,$input),
177 elsif ( $phase eq 'Choose these columns' ) {
179 # we now know type, area, and columns
180 # next step is the constraints
181 my $area = $input->param('area');
182 my $type = $input->param('type');
183 my @columns = $input->param('columns');
184 my $column = join( ',', @columns );
190 definitions => get_from_dictionary($area),
191 criteria => get_criteria($area,$input),
195 elsif ( $phase eq 'Choose these criteria' ) {
196 my $area = $input->param('area');
197 my $type = $input->param('type');
198 my $column = $input->param('column');
199 my @definitions = $input->param('definition');
200 my $definition = join (',',@definitions);
201 my @criteria = $input->param('criteria_column');
203 foreach my $crit (@criteria) {
204 my $value = $input->param( $crit . "_value" );
206 # If value is not defined, then it may be range values
207 if (!defined $value) {
209 my $fromvalue = $input->param( "from_" . $crit . "_value" );
210 my $tovalue = $input->param( "to_" . $crit . "_value" );
212 # If the range values are dates
213 if ($fromvalue =~ C4::Dates->regexp('syspref') && $tovalue =~ C4::Dates->regexp('syspref')) {
214 $fromvalue = C4::Dates->new($fromvalue)->output("iso");
215 $tovalue = C4::Dates->new($tovalue)->output("iso");
218 if ($fromvalue && $tovalue) {
219 $query_criteria .= " AND $crit >= '$fromvalue' AND $crit <= '$tovalue'";
225 if ($value =~ C4::Dates->regexp('syspref')) {
226 $value = C4::Dates->new($value)->output("iso");
228 # don't escape runtime parameters, they'll be at runtime
229 if ($value =~ /<<.*>>/) {
230 $query_criteria .= " AND $crit=$value";
232 $query_criteria .= " AND $crit='$value'";
242 'definition' => $definition,
243 'criteriastring' => $query_criteria,
247 my @columns = split( ',', $column );
250 # build structue for use by tmpl_loop to choose columns to order by
251 # need to do something about the order of the order :)
252 # we also want to use the %columns hash to get the plain english names
253 foreach my $col (@columns) {
254 my %total = (name => $col);
255 my @selects = map {+{ value => $_ }} (qw(sum min max avg count));
256 $total{'select'} = \@selects;
257 push @total_by, \%total;
260 $template->param( 'total_by' => \@total_by );
263 elsif ( $phase eq 'Choose These Operations' ) {
264 my $area = $input->param('area');
265 my $type = $input->param('type');
266 my $column = $input->param('column');
267 my $criteria = $input->param('criteria');
268 my $definition = $input->param('definition');
269 my @total_by = $input->param('total_by');
271 foreach my $total (@total_by) {
272 my $value = $input->param( $total . "_tvalue" );
273 $totals .= "$value($total),";
281 'criteriastring' => $criteria,
283 'definition' => $definition,
287 my @columns = split( ',', $column );
290 # build structue for use by tmpl_loop to choose columns to order by
291 # need to do something about the order of the order :)
292 foreach my $col (@columns) {
293 my %order = (name => $col);
294 my @selects = map {+{ value => $_ }} (qw(asc desc));
295 $order{'select'} = \@selects;
296 push @order_by, \%order;
299 $template->param( 'order_by' => \@order_by );
302 elsif ( $phase eq 'Build Report' ) {
304 # now we have all the info we need and can build the sql
305 my $area = $input->param('area');
306 my $type = $input->param('type');
307 my $column = $input->param('column');
308 my $crit = $input->param('criteria');
309 my $totals = $input->param('totals');
310 my $definition = $input->param('definition');
311 my $query_criteria=$crit;
312 # split the columns up by ,
313 my @columns = split( ',', $column );
314 my @order_by = $input->param('order_by');
317 foreach my $order (@order_by) {
318 my $value = $input->param( $order . "_ovalue" );
319 if ($query_orderby) {
320 $query_orderby .= ",$order $value";
323 $query_orderby = " ORDER BY $order $value";
329 build_query( \@columns, $query_criteria, $query_orderby, $area, $totals, $definition );
337 elsif ( $phase eq 'Save' ) {
338 # Save the report that has just been built
339 my $sql = $input->param('sql');
340 my $type = $input->param('type');
348 elsif ( $phase eq 'Save Report' ) {
349 # save the sql pasted in by a user
350 my $sql = $input->param('sql');
351 my $name = $input->param('reportname');
352 my $type = $input->param('types');
353 my $notes = $input->param('notes');
354 if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
355 push @errors, {sqlerr => $1};
357 elsif ($sql !~ /^(SELECT)/i) {
358 push @errors, {queryerr => 1};
362 'errors' => \@errors,
364 'reportname'=> $name,
370 my $id = save_report( $borrowernumber, $sql, $name, $type, $notes );
372 'save_successful' => 1,
378 elsif ($phase eq 'Run this report'){
379 # execute a saved report
380 my $limit = 20; # page size. # TODO: move to DB or syspref?
382 my $report = $input->param('reports');
383 my @sql_params = $input->param('sql_params');
385 if ($input->param('page')) {
386 $offset = ($input->param('page') - 1) * $limit;
388 my ($sql,$type,$name,$notes) = get_saved_report($report);
390 push @errors, {no_sql_for_id=>$report};
393 # if we have at least 1 parameter, and it's not filled, then don't execute but ask for parameters
394 if ($sql =~ /<</ && !@sql_params) {
395 # split on ??. Each odd (2,4,6,...) entry should be a parameter to fill
396 my @split = split /<<|>>/,$sql;
398 for(my $i=0;$i<($#split/2);$i++) {
399 my ($text,$authorised_value) = split /\|/,$split[$i*2+1];
401 if ($authorised_value) {
402 my $dbh=C4::Context->dbh;
403 my @authorised_values;
405 # builds list, depending on authorised value...
406 if ( $authorised_value eq "branches" ) {
407 my $branches = GetBranchesLoop();
408 foreach my $thisbranch (@$branches) {
409 push @authorised_values, $thisbranch->{value};
410 $authorised_lib{$thisbranch->{value}} = $thisbranch->{branchname};
413 elsif ( $authorised_value eq "itemtypes" ) {
414 my $sth = $dbh->prepare("SELECT itemtype,description FROM itemtypes ORDER BY description");
416 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
417 push @authorised_values, $itemtype;
418 $authorised_lib{$itemtype} = $description;
421 elsif ( $authorised_value eq "cn_source" ) {
422 my $class_sources = GetClassSources();
423 my $default_source = C4::Context->preference("DefaultClassificationSource");
424 foreach my $class_source (sort keys %$class_sources) {
425 next unless $class_sources->{$class_source}->{'used'} or
426 ($class_source eq $default_source);
427 push @authorised_values, $class_source;
428 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
431 elsif ( $authorised_value eq "categorycode" ) {
432 my $sth = $dbh->prepare("SELECT categorycode, description FROM categories ORDER BY description");
434 while ( my ( $categorycode, $description ) = $sth->fetchrow_array ) {
435 push @authorised_values, $categorycode;
436 $authorised_lib{$categorycode} = $description;
439 #---- "true" authorised value
442 my $authorised_values_sth = $dbh->prepare("SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib");
444 $authorised_values_sth->execute( $authorised_value);
446 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
447 push @authorised_values, $value;
448 $authorised_lib{$value} = $lib;
449 # For item location, we show the code and the libelle
450 $authorised_lib{$value} = $lib;
453 $input =CGI::scrolling_list( # FIXME: factor out scrolling_list
454 -name => "sql_params",
455 -values => \@authorised_values,
456 # -default => $value,
457 -labels => \%authorised_lib,
465 $input = "<input type='text' name='sql_params'/>";
467 push @tmpl_parameters, {'entry' => $text, 'input' => $input };
469 $template->param('sql' => $sql,
471 'sql_params' => \@tmpl_parameters,
473 'reports' => $report,
476 # OK, we have parameters, or there are none, we run the report
477 # if there were parameters, replace before running
478 # split on ??. Each odd (2,4,6,...) entry should be a parameter to fill
479 my @split = split /<<|>>/,$sql;
481 for(my $i=0;$i<$#split/2;$i++) {
482 my $quoted = C4::Context->dbh->quote($sql_params[$i]);
483 # if there are special regexp chars, we must \ them
484 $split[$i*2+1] =~ s/(\||\?|\.|\*|\(|\)|\%)/\\$1/g;
485 $sql =~ s/<<$split[$i*2+1]>>/$quoted/;
487 my ($sth, $errors) = execute_query($sql, $offset, $limit);
488 my $total = nb_rows($sql) || 0;
490 die "execute_query failed to return sth for report $report: $sql";
492 my $headref = $sth->{NAME} || [];
493 my @headers = map { +{ cell => $_ } } @$headref;
494 $template->param(header_row => \@headers);
495 while (my $row = $sth->fetchrow_arrayref()) {
496 my @cells = map { +{ cell => $_ } } @$row;
497 push @rows, { cells => \@cells };
501 my $totpages = int($total/$limit) + (($total % $limit) > 0 ? 1 : 0);
502 my $url = "/cgi-bin/koha/reports/guided_reports.pl?reports=$report&phase=Run%20this%20report";
510 'pagination_bar' => pagination_bar($url, $totpages, $input->param('page')),
511 'unlimited_total' => $total,
516 elsif ($phase eq 'Export'){
517 binmode STDOUT, ':utf8';
519 # export results to tab separated text or CSV
520 my $sql = $input->param('sql'); # FIXME: use sql from saved report ID#, not new user-supplied SQL!
521 my $format = $input->param('format');
522 my ($sth, $q_errors) = execute_query($sql);
523 unless ($q_errors and @$q_errors) {
524 print $input->header( -type => 'application/octet-stream',
525 -attachment=>"reportresults.$format"
527 if ($format eq 'tab') {
528 print join("\t", header_cell_values($sth)), "\n";
529 while (my $row = $sth->fetchrow_arrayref()) {
530 print join("\t", @$row), "\n";
533 my $csv = Text::CSV->new({binary => 1});
534 $csv or die "Text::CSV->new({binary => 1}) FAILED: " . Text::CSV->error_diag();
535 if ($csv->combine(header_cell_values($sth))) {
536 print $csv->string(), "\n";
538 push @$q_errors, { combine => 'HEADER ROW: ' . $csv->error_diag() } ;
540 while (my $row = $sth->fetchrow_arrayref()) {
541 if ($csv->combine(@$row)) {
542 print $csv->string(), "\n";
544 push @$q_errors, { combine => $csv->error_diag() } ;
548 foreach my $err (@$q_errors, @errors) {
549 print "# ERROR: " . (map {$_ . ": " . $err->{$_}} keys %$err) . "\n";
550 } # here we print all the non-fatal errors at the end. Not super smooth, but better than nothing.
556 'name' => 'Error exporting report!',
558 'errors' => $q_errors,
562 elsif ($phase eq 'Create report from SQL') {
563 # allow the user to paste in sql
564 if ($input->param('sql')) {
566 'sql' => $input->param('sql'),
567 'reportname' => $input->param('reportname'),
568 'notes' => $input->param('notes'),
571 $template->param('create' => 1);
574 elsif ($phase eq 'Create Compound Report'){
575 $template->param( 'savedreports' => get_saved_reports(),
580 elsif ($phase eq 'Save Compound'){
581 my $master = $input->param('master');
582 my $subreport = $input->param('subreport');
583 my ($mastertables,$subtables) = create_compound($master,$subreport);
584 $template->param( 'save_compound' => 1,
585 master=>$mastertables,
590 # pass $sth, get back an array of names for the column headers
591 sub header_cell_values {
592 my $sth = shift or return ();
593 return @{$sth->{NAME}};
596 # pass $sth, get back a TMPL_LOOP-able set of names for the column headers
597 sub header_cell_loop {
598 my @headers = map { +{ cell => $_ } } header_cell_values (shift);
603 $template->param('build' . $_) and $template->param(buildx => $_) and last;
605 $template->param( 'referer' => $input->referer(),
606 'DHTMLcalendar_dateformat' => C4::Dates->DHTMLcalendar(),
609 output_html_with_http_headers $input, $cookie, $template->output;