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
45 my $phase = $input->param('phase');
47 if ( $phase eq 'Build new' ) {
48 $flagsrequired = 'create_report';
50 elsif ( $phase eq 'Use saved' ) {
51 $flagsrequired = 'execute_report';
56 my ( $template, $borrowernumber, $cookie ) = get_template_and_user
(
58 template_name
=> "reports/guided_reports_start.tmpl",
62 flagsrequired
=> { reports
=> $flagsrequired },
69 $template->param( 'start' => 1 );
72 elsif ( $phase eq 'Build new' ) {
74 $template->param( 'build1' => 1 );
75 $template->param( 'areas' => get_report_areas
() );
77 elsif ( $phase eq 'Use saved' ) {
79 # get list of reports and display them
80 $template->param( 'saved1' => 1 );
81 $template->param( 'savedreports' => get_saved_reports
() );
84 elsif ( $phase eq 'Delete Saved') {
86 # delete a report from the saved reports list
87 my $id = $input->param('reports');
89 print $input->redirect("/cgi-bin/koha/reports/guided_reports.pl?phase=Use%20saved");
93 elsif ( $phase eq 'Show SQL'){
95 my $id = $input->param('reports');
96 my $sql = get_sql
($id);
103 elsif ( $phase eq 'Edit SQL'){
105 my $id = $input->param('reports');
106 my ($sql,$type,$reportname,$notes) = get_saved_report
($id);
109 'reportname' => $reportname,
116 elsif ( $phase eq 'Update SQL'){
117 my $id = $input->param('id');
118 my $sql = $input->param('sql');
119 my $reportname = $input->param('reportname');
120 my $notes = $input->param('notes');
122 if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
123 push @errors, {sqlerr
=> $1};
125 elsif ($sql !~ /^(SELECT)/i) {
126 push @errors, {queryerr
=> 1};
130 'errors' => \
@errors,
135 update_sql
( $id, $sql, $reportname, $notes );
137 'save_successful' => 1,
143 elsif ($phase eq 'retrieve results') {
144 my $id = $input->param('id');
145 my ($results,$name,$notes) = format_results
($id);
149 'results' => $results,
155 elsif ( $phase eq 'Report on this Area' ) {
157 # they have choosen a new report and the area to report on
160 'area' => $input->param('areas'),
161 'types' => get_report_types
(),
165 elsif ( $phase eq 'Choose this type' ) {
167 # they have chosen type and area
168 # get area and type and pass them to the template
169 my $area = $input->param('area');
170 my $type = $input->param('types');
175 columns
=> get_columns
($area,$input),
179 elsif ( $phase eq 'Choose these columns' ) {
181 # we now know type, area, and columns
182 # next step is the constraints
183 my $area = $input->param('area');
184 my $type = $input->param('type');
185 my @columns = $input->param('columns');
186 my $column = join( ',', @columns );
192 definitions
=> get_from_dictionary
($area),
193 criteria
=> get_criteria
($area,$input),
197 elsif ( $phase eq 'Choose these criteria' ) {
198 my $area = $input->param('area');
199 my $type = $input->param('type');
200 my $column = $input->param('column');
201 my @definitions = $input->param('definition');
202 my $definition = join (',',@definitions);
203 my @criteria = $input->param('criteria_column');
205 foreach my $crit (@criteria) {
206 my $value = $input->param( $crit . "_value" );
208 # If value is not defined, then it may be range values
209 if (!defined $value) {
211 my $fromvalue = $input->param( "from_" . $crit . "_value" );
212 my $tovalue = $input->param( "to_" . $crit . "_value" );
214 # If the range values are dates
215 if ($fromvalue =~ C4
::Dates
->regexp('syspref') && $tovalue =~ C4
::Dates
->regexp('syspref')) {
216 $fromvalue = C4
::Dates
->new($fromvalue)->output("iso");
217 $tovalue = C4
::Dates
->new($tovalue)->output("iso");
220 if ($fromvalue && $tovalue) {
221 $query_criteria .= " AND $crit >= '$fromvalue' AND $crit <= '$tovalue'";
227 if ($value =~ C4
::Dates
->regexp('syspref')) {
228 $value = C4
::Dates
->new($value)->output("iso");
230 # don't escape runtime parameters, they'll be at runtime
231 if ($value =~ /<<.*>>/) {
232 $query_criteria .= " AND $crit=$value";
234 $query_criteria .= " AND $crit='$value'";
244 'definition' => $definition,
245 'criteriastring' => $query_criteria,
249 my @columns = split( ',', $column );
252 # build structue for use by tmpl_loop to choose columns to order by
253 # need to do something about the order of the order :)
254 # we also want to use the %columns hash to get the plain english names
255 foreach my $col (@columns) {
256 my %total = (name
=> $col);
257 my @selects = map {+{ value
=> $_ }} (qw(sum min max avg count));
258 $total{'select'} = \
@selects;
259 push @total_by, \
%total;
262 $template->param( 'total_by' => \
@total_by );
265 elsif ( $phase eq 'Choose These Operations' ) {
266 my $area = $input->param('area');
267 my $type = $input->param('type');
268 my $column = $input->param('column');
269 my $criteria = $input->param('criteria');
270 my $definition = $input->param('definition');
271 my @total_by = $input->param('total_by');
273 foreach my $total (@total_by) {
274 my $value = $input->param( $total . "_tvalue" );
275 $totals .= "$value($total),";
283 'criteriastring' => $criteria,
285 'definition' => $definition,
289 my @columns = split( ',', $column );
292 # build structue for use by tmpl_loop to choose columns to order by
293 # need to do something about the order of the order :)
294 foreach my $col (@columns) {
295 my %order = (name
=> $col);
296 my @selects = map {+{ value
=> $_ }} (qw(asc desc));
297 $order{'select'} = \
@selects;
298 push @order_by, \
%order;
301 $template->param( 'order_by' => \
@order_by );
304 elsif ( $phase eq 'Build Report' ) {
306 # now we have all the info we need and can build the sql
307 my $area = $input->param('area');
308 my $type = $input->param('type');
309 my $column = $input->param('column');
310 my $crit = $input->param('criteria');
311 my $totals = $input->param('totals');
312 my $definition = $input->param('definition');
313 my $query_criteria=$crit;
314 # split the columns up by ,
315 my @columns = split( ',', $column );
316 my @order_by = $input->param('order_by');
319 foreach my $order (@order_by) {
320 my $value = $input->param( $order . "_ovalue" );
321 if ($query_orderby) {
322 $query_orderby .= ",$order $value";
325 $query_orderby = " ORDER BY $order $value";
331 build_query
( \
@columns, $query_criteria, $query_orderby, $area, $totals, $definition );
339 elsif ( $phase eq 'Save' ) {
340 # Save the report that has just been built
341 my $sql = $input->param('sql');
342 my $type = $input->param('type');
350 elsif ( $phase eq 'Save Report' ) {
351 # save the sql pasted in by a user
352 my $sql = $input->param('sql');
353 my $name = $input->param('reportname');
354 my $type = $input->param('types');
355 my $notes = $input->param('notes');
356 if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
357 push @errors, {sqlerr
=> $1};
359 elsif ($sql !~ /^(SELECT)/i) {
360 push @errors, {queryerr
=> 1};
364 'errors' => \
@errors,
366 'reportname'=> $name,
372 save_report
( $borrowernumber, $sql, $name, $type, $notes );
374 'save_successful' => 1,
379 elsif ($phase eq 'Run this report'){
380 # execute a saved report
381 my $limit = 20; # page size. # TODO: move to DB or syspref?
383 my $report = $input->param('reports');
384 my @sql_params = $input->param('sql_params');
386 if ($input->param('page')) {
387 $offset = ($input->param('page') - 1) * $limit;
389 my ($sql,$type,$name,$notes) = get_saved_report
($report);
391 push @errors, {no_sql_for_id
=>$report};
394 # if we have at least 1 parameter, and it's not filled, then don't execute but ask for parameters
395 if ($sql =~ /<</ && !@sql_params) {
396 # split on ??. Each odd (2,4,6,...) entry should be a parameter to fill
397 my @split = split /<<|>>/,$sql;
399 for(my $i=0;$i<($#split/2);$i++) {
400 my ($text,$authorised_value) = split /\|/,$split[$i*2+1];
402 if ($authorised_value) {
403 my $dbh=C4
::Context
->dbh;
404 my @authorised_values;
406 # builds list, depending on authorised value...
407 if ( $authorised_value eq "branches" ) {
408 my $branches = GetBranchesLoop
();
409 foreach my $thisbranch (@
$branches) {
410 push @authorised_values, $thisbranch->{value
};
411 $authorised_lib{$thisbranch->{value
}} = $thisbranch->{branchname
};
414 elsif ( $authorised_value eq "itemtypes" ) {
415 my $sth = $dbh->prepare("SELECT itemtype,description FROM itemtypes ORDER BY description");
417 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
418 push @authorised_values, $itemtype;
419 $authorised_lib{$itemtype} = $description;
422 elsif ( $authorised_value eq "cn_source" ) {
423 my $class_sources = GetClassSources
();
424 my $default_source = C4
::Context
->preference("DefaultClassificationSource");
425 foreach my $class_source (sort keys %$class_sources) {
426 next unless $class_sources->{$class_source}->{'used'} or
427 ($class_source eq $default_source);
428 push @authorised_values, $class_source;
429 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
432 elsif ( $authorised_value eq "categorycode" ) {
433 my $sth = $dbh->prepare("SELECT categorycode, description FROM categories ORDER BY description");
435 while ( my ( $categorycode, $description ) = $sth->fetchrow_array ) {
436 push @authorised_values, $categorycode;
437 $authorised_lib{$categorycode} = $description;
440 #---- "true" authorised value
443 my $authorised_values_sth = $dbh->prepare("SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib");
445 $authorised_values_sth->execute( $authorised_value);
447 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
448 push @authorised_values, $value;
449 $authorised_lib{$value} = $lib;
450 # For item location, we show the code and the libelle
451 $authorised_lib{$value} = $lib;
454 $input =CGI
::scrolling_list
( # FIXME: factor out scrolling_list
455 -name
=> "sql_params",
456 -values => \
@authorised_values,
457 # -default => $value,
458 -labels
=> \
%authorised_lib,
466 $input = "<input type='text' name='sql_params'/>";
468 push @tmpl_parameters, {'entry' => $text, 'input' => $input };
470 $template->param('sql' => $sql,
472 'sql_params' => \
@tmpl_parameters,
474 'reports' => $report,
477 # OK, we have parameters, or there are none, we run the report
478 # if there were parameters, replace before running
479 # split on ??. Each odd (2,4,6,...) entry should be a parameter to fill
480 my @split = split /<<|>>/,$sql;
482 for(my $i=0;$i<$#split/2;$i++) {
483 my $quoted = C4
::Context
->dbh->quote($sql_params[$i]);
484 # if there are special regexp chars, we must \ them
485 $split[$i*2+1] =~ s/(\||\?|\.|\*|\(|\)|\%)/\\$1/g;
486 $sql =~ s/<<$split[$i*2+1]>>/$quoted/;
488 my ($sth, $errors) = execute_query
($sql, $offset, $limit);
489 my $total = select_2_select_count_value
($sql) || 0;
491 die "execute_query failed to return sth for report $report: $sql";
493 my $headref = $sth->{NAME
} || [];
494 my @headers = map { +{ cell
=> $_ } } @
$headref;
495 $template->param(header_row
=> \
@headers);
496 while (my $row = $sth->fetchrow_arrayref()) {
497 my @cells = map { +{ cell
=> $_ } } @
$row;
498 push @rows, { cells
=> \
@cells };
502 my $totpages = int($total/$limit) + (($total % $limit) > 0 ?
1 : 0);
503 my $url = "/cgi-bin/koha/reports/guided_reports.pl?reports=$report&phase=Run%20this%20report";
511 'pagination_bar' => pagination_bar
($url, $totpages, $input->param('page')),
512 'unlimited_total' => $total,
517 elsif ($phase eq 'Export'){
518 binmode STDOUT
, ':utf8';
520 # export results to tab separated text or CSV
521 my $sql = $input->param('sql'); # FIXME: use sql from saved report ID#, not new user-supplied SQL!
522 my $format = $input->param('format');
523 my ($sth, $q_errors) = execute_query
($sql);
524 unless ($q_errors and @
$q_errors) {
525 print $input->header( -type
=> 'application/octet-stream',
526 -attachment
=>"reportresults.$format"
528 if ($format eq 'tab') {
529 print join("\t", header_cell_values
($sth)), "\n";
530 while (my $row = $sth->fetchrow_arrayref()) {
531 print join("\t", @
$row), "\n";
534 my $csv = Text
::CSV
->new({binary
=> 1});
535 $csv or die "Text::CSV->new({binary => 1}) FAILED: " . Text
::CSV
->error_diag();
536 if ($csv->combine(header_cell_values
($sth))) {
537 print $csv->string(), "\n";
539 push @
$q_errors, { combine
=> 'HEADER ROW: ' . $csv->error_diag() } ;
541 while (my $row = $sth->fetchrow_arrayref()) {
542 if ($csv->combine(@
$row)) {
543 print $csv->string(), "\n";
545 push @
$q_errors, { combine
=> $csv->error_diag() } ;
549 foreach my $err (@
$q_errors, @errors) {
550 print "# ERROR: " . (map {$_ . ": " . $err->{$_}} keys %$err) . "\n";
551 } # here we print all the non-fatal errors at the end. Not super smooth, but better than nothing.
557 'name' => 'Error exporting report!',
559 'errors' => $q_errors,
563 elsif ($phase eq 'Create report from SQL') {
564 # allow the user to paste in sql
565 if ($input->param('sql')) {
567 'sql' => $input->param('sql'),
568 'reportname' => $input->param('reportname'),
569 'notes' => $input->param('notes'),
572 $template->param('create' => 1);
575 elsif ($phase eq 'Create Compound Report'){
576 $template->param( 'savedreports' => get_saved_reports
(),
581 elsif ($phase eq 'Save Compound'){
582 my $master = $input->param('master');
583 my $subreport = $input->param('subreport');
584 my ($mastertables,$subtables) = create_compound
($master,$subreport);
585 $template->param( 'save_compound' => 1,
586 master
=>$mastertables,
591 # pass $sth, get back an array of names for the column headers
592 sub header_cell_values
{
593 my $sth = shift or return ();
594 return @
{$sth->{NAME
}};
597 # pass $sth, get back a TMPL_LOOP-able set of names for the column headers
598 sub header_cell_loop
{
599 my @headers = map { +{ cell
=> $_ } } header_cell_values
(shift);
604 $template->param('build' . $_) and $template->param(buildx
=> $_) and last;
606 $template->param( 'referer' => $input->referer(),
607 'DHTMLcalendar_dateformat' => C4
::Dates
->DHTMLcalendar(),
610 output_html_with_http_headers
$input, $cookie, $template->output;