Bug 17216: Do no display the empty string category name
[koha.git] / C4 / Reports / Guided.pm
1 package C4::Reports::Guided;
2
3 # Copyright 2007 Liblime Ltd
4 #
5 # This file is part of Koha.
6 #
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.
11 #
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.
16 #
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>.
19
20 use Modern::Perl;
21 use CGI qw ( -utf8 );
22 use Carp;
23 use JSON qw( from_json );
24
25 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
26 use C4::Context;
27 use C4::Templates qw/themelanguage/;
28 use C4::Koha;
29 use Koha::DateUtils;
30 use C4::Output;
31 use C4::Debug;
32 use C4::Log;
33
34 use Koha::AuthorisedValues;
35 use Koha::Patron::Categories;
36
37 BEGIN {
38     require Exporter;
39     @ISA    = qw(Exporter);
40     @EXPORT = qw(
41       get_report_types get_report_areas get_report_groups get_columns build_query get_criteria
42       save_report get_saved_reports execute_query get_saved_report create_compound run_compound
43       get_column_type get_distinct_values save_dictionary get_from_dictionary
44       delete_definition delete_report format_results get_sql
45       nb_rows update_sql
46       GetReservedAuthorisedValues
47       GetParametersFromSQL
48       IsAuthorisedValueValid
49       ValidateSQLParameters
50       nb_rows update_sql
51     );
52 }
53
54 =head1 NAME
55
56 C4::Reports::Guided - Module for generating guided reports 
57
58 =head1 SYNOPSIS
59
60   use C4::Reports::Guided;
61
62 =head1 DESCRIPTION
63
64 =cut
65
66 =head1 METHODS
67
68 =head2 get_report_areas
69
70 This will return a list of all the available report areas
71
72 =cut
73
74 sub get_area_name_sql_snippet {
75     my @REPORT_AREA = (
76         [CIRC => "Circulation"],
77         [CAT  => "Catalogue"],
78         [PAT  => "Patrons"],
79         [ACQ  => "Acquisition"],
80         [ACC  => "Accounts"],
81         [SER  => "Serials"],
82     );
83
84     return "CASE report_area " .
85     join (" ", map "WHEN '$_->[0]' THEN '$_->[1]'", @REPORT_AREA) .
86     " END AS areaname";
87 }
88
89 sub get_report_areas {
90
91     my $report_areas = [ 'CIRC', 'CAT', 'PAT', 'ACQ', 'ACC', 'SER' ];
92
93     return $report_areas;
94 }
95
96 sub get_table_areas {
97     return (
98     CIRC => [ 'borrowers', 'statistics', 'items', 'biblioitems' ],
99     CAT  => [ 'items', 'biblioitems', 'biblio' ],
100     PAT  => ['borrowers'],
101     ACQ  => [ 'aqorders', 'biblio', 'items' ],
102     ACC  => [ 'borrowers', 'accountlines' ],
103     SER  => [ 'serial', 'serialitems', 'subscription', 'subscriptionhistory', 'subscriptionroutinglist', 'biblioitems', 'biblio', 'aqbooksellers' ],
104     );
105 }
106
107 =head2 get_report_types
108
109 This will return a list of all the available report types
110
111 =cut
112
113 sub get_report_types {
114     my $dbh = C4::Context->dbh();
115
116     # FIXME these should be in the database perhaps
117     my @reports = ( 'Tabular', 'Summary', 'Matrix' );
118     my @reports2;
119     for ( my $i = 0 ; $i < 3 ; $i++ ) {
120         my %hashrep;
121         $hashrep{id}   = $i + 1;
122         $hashrep{name} = $reports[$i];
123         push @reports2, \%hashrep;
124     }
125     return ( \@reports2 );
126
127 }
128
129 =head2 get_report_groups
130
131 This will return a list of all the available report areas with groups
132
133 =cut
134
135 sub get_report_groups {
136     my $dbh = C4::Context->dbh();
137
138     my $groups = GetAuthorisedValues('REPORT_GROUP');
139     my $subgroups = GetAuthorisedValues('REPORT_SUBGROUP');
140
141     my %groups_with_subgroups = map { $_->{authorised_value} => {
142                         name => $_->{lib},
143                         groups => {}
144                     } } @$groups;
145     foreach (@$subgroups) {
146         my $sg = $_->{authorised_value};
147         my $g = $_->{lib_opac}
148           or warn( qq{REPORT_SUBGROUP "$sg" without REPORT_GROUP (lib_opac)} ),
149              next;
150         my $g_sg = $groups_with_subgroups{$g}
151           or warn( qq{REPORT_SUBGROUP "$sg" with invalid REPORT_GROUP "$g"} ),
152              next;
153         $g_sg->{subgroups}{$sg} = $_->{lib};
154     }
155     return \%groups_with_subgroups
156 }
157
158 =head2 get_all_tables
159
160 This will return a list of all tables in the database 
161
162 =cut
163
164 sub get_all_tables {
165     my $dbh   = C4::Context->dbh();
166     my $query = "SHOW TABLES";
167     my $sth   = $dbh->prepare($query);
168     $sth->execute();
169     my @tables;
170     while ( my $data = $sth->fetchrow_arrayref() ) {
171         push @tables, $data->[0];
172     }
173     $sth->finish();
174     return ( \@tables );
175
176 }
177
178 =head2 get_columns($area)
179
180 This will return a list of all columns for a report area
181
182 =cut
183
184 sub get_columns {
185
186     # this calls the internal function _get_columns
187     my ( $area, $cgi ) = @_;
188     my %table_areas = get_table_areas;
189     my $tables = $table_areas{$area}
190       or die qq{Unsuported report area "$area"};
191
192     my @allcolumns;
193     my $first = 1;
194     foreach my $table (@$tables) {
195         my @columns = _get_columns($table,$cgi, $first);
196         $first = 0;
197         push @allcolumns, @columns;
198     }
199     return ( \@allcolumns );
200 }
201
202 sub _get_columns {
203     my ($tablename,$cgi, $first) = @_;
204     my $dbh         = C4::Context->dbh();
205     my $sth         = $dbh->prepare("show columns from $tablename");
206     $sth->execute();
207     my @columns;
208         my $column_defs = _get_column_defs($cgi);
209         my %tablehash;
210         $tablehash{'table'}=$tablename;
211     $tablehash{'__first__'} = $first;
212         push @columns, \%tablehash;
213     while ( my $data = $sth->fetchrow_arrayref() ) {
214         my %temphash;
215         $temphash{'name'}        = "$tablename.$data->[0]";
216         $temphash{'description'} = $column_defs->{"$tablename.$data->[0]"};
217         push @columns, \%temphash;
218     }
219     $sth->finish();
220     return (@columns);
221 }
222
223 =head2 build_query($columns,$criteria,$orderby,$area)
224
225 This will build the sql needed to return the results asked for, 
226 $columns is expected to be of the format tablename.columnname.
227 This is what get_columns returns.
228
229 =cut
230
231 sub build_query {
232     my ( $columns, $criteria, $orderby, $area, $totals, $definition ) = @_;
233
234     my %keys = (
235         CIRC => [ 'statistics.borrowernumber=borrowers.borrowernumber',
236                   'items.itemnumber = statistics.itemnumber',
237                   'biblioitems.biblioitemnumber = items.biblioitemnumber' ],
238         CAT  => [ 'items.biblioitemnumber=biblioitems.biblioitemnumber',
239                   'biblioitems.biblionumber=biblio.biblionumber' ],
240         PAT  => [],
241         ACQ  => [ 'aqorders.biblionumber=biblio.biblionumber',
242                   'biblio.biblionumber=items.biblionumber' ],
243         ACC  => ['borrowers.borrowernumber=accountlines.borrowernumber'],
244         SER  => [ 'serial.serialid=serialitems.serialid', 'serial.subscriptionid=subscription.subscriptionid', 'serial.subscriptionid=subscriptionhistory.subscriptionid', 'serial.subscriptionid=subscriptionroutinglist.subscriptionid', 'biblioitems.biblionumber=serial.biblionumber', 'biblio.biblionumber=biblioitems.biblionumber', 'subscription.aqbooksellerid=aqbooksellers.id'],
245     );
246
247
248 ### $orderby
249     my $keys   = $keys{$area};
250     my %table_areas = get_table_areas;
251     my $tables = $table_areas{$area};
252
253     my $sql =
254       _build_query( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition );
255     return ($sql);
256 }
257
258 sub _build_query {
259     my ( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition) = @_;
260 ### $orderby
261     # $keys is an array of joining constraints
262     my $dbh           = C4::Context->dbh();
263     my $joinedtables  = join( ',', @$tables );
264     my $joinedcolumns = join( ',', @$columns );
265     my $query =
266       "SELECT $totals $joinedcolumns FROM $tables->[0] ";
267         for (my $i=1;$i<@$tables;$i++){
268                 $query .= "LEFT JOIN $tables->[$i] on ($keys->[$i-1]) ";
269         }
270
271     if ($criteria) {
272                 $criteria =~ s/AND/WHERE/;
273         $query .= " $criteria";
274     }
275         if ($definition){
276                 my @definitions = split(',',$definition);
277                 my $deftext;
278                 foreach my $def (@definitions){
279                         my $defin=get_from_dictionary('',$def);
280                         $deftext .=" ".$defin->[0]->{'saved_sql'};
281                 }
282                 if ($query =~ /WHERE/i){
283                         $query .= $deftext;
284                 }
285                 else {
286                         $deftext  =~ s/AND/WHERE/;
287                         $query .= $deftext;                     
288                 }
289         }
290     if ($totals) {
291         my $groupby;
292         my @totcolumns = split( ',', $totals );
293         foreach my $total (@totcolumns) {
294             if ( $total =~ /\((.*)\)/ ) {
295                 if ( $groupby eq '' ) {
296                     $groupby = " GROUP BY $1";
297                 }
298                 else {
299                     $groupby .= ",$1";
300                 }
301             }
302         }
303         $query .= $groupby;
304     }
305     if ($orderby) {
306         $query .= $orderby;
307     }
308     return ($query);
309 }
310
311 =head2 get_criteria($area,$cgi);
312
313 Returns an arraref to hashrefs suitable for using in a tmpl_loop. With the criteria and available values.
314
315 =cut
316
317 sub get_criteria {
318     my ($area,$cgi) = @_;
319     my $dbh    = C4::Context->dbh();
320
321     # have to do someting here to know if its dropdown, free text, date etc
322     my %criteria = (
323         CIRC => [ 'statistics.type', 'borrowers.categorycode', 'statistics.branch',
324                   'biblioitems.publicationyear|date', 'items.dateaccessioned|date' ],
325         CAT  => [ 'items.itemnumber|textrange', 'items.biblionumber|textrange',
326                   'items.barcode|textrange', 'biblio.frameworkcode',
327                   'items.holdingbranch', 'items.homebranch',
328                   'biblio.datecreated|daterange', 'biblio.timestamp|daterange',
329                   'items.onloan|daterange', 'items.ccode',
330                   'items.itemcallnumber|textrange', 'items.itype', 'items.itemlost',
331                   'items.location' ],
332         PAT  => [ 'borrowers.branchcode', 'borrowers.categorycode' ],
333         ACQ  => ['aqorders.datereceived|date'],
334         ACC  => [ 'borrowers.branchcode', 'borrowers.categorycode' ],
335         SER  => ['subscription.startdate|date', 'subscription.enddate|date', 'subscription.periodicity', 'subscription.callnumber', 'subscription.location', 'subscription.branchcode'],
336     );
337
338     # Adds itemtypes to criteria, according to the syspref
339     if ( C4::Context->preference('item-level_itypes') ) {
340         unshift @{ $criteria{'CIRC'} }, 'items.itype';
341         unshift @{ $criteria{'CAT'} }, 'items.itype';
342     } else {
343         unshift @{ $criteria{'CIRC'} }, 'biblioitems.itemtype';
344         unshift @{ $criteria{'CAT'} }, 'biblioitems.itemtype';
345     }
346
347
348     my $crit   = $criteria{$area};
349     my $column_defs = _get_column_defs($cgi);
350     my @criteria_array;
351     foreach my $localcrit (@$crit) {
352         my ( $value, $type )   = split( /\|/, $localcrit );
353         my ( $table, $column ) = split( /\./, $value );
354         if ($type eq 'textrange') {
355             my %temp;
356             $temp{'name'}        = $value;
357             $temp{'from'}        = "from_" . $value;
358             $temp{'to'}          = "to_" . $value;
359             $temp{'textrange'}   = 1;
360             $temp{'description'} = $column_defs->{$value};
361             push @criteria_array, \%temp;
362         }
363         elsif ($type eq 'date') {
364             my %temp;
365             $temp{'name'}        = $value;
366             $temp{'date'}        = 1;
367             $temp{'description'} = $column_defs->{$value};
368             push @criteria_array, \%temp;
369         }
370         elsif ($type eq 'daterange') {
371             my %temp;
372             $temp{'name'}        = $value;
373             $temp{'from'}        = "from_" . $value;
374             $temp{'to'}          = "to_" . $value;
375             $temp{'daterange'}   = 1;
376             $temp{'description'} = $column_defs->{$value};
377             push @criteria_array, \%temp;
378         }
379         else {
380             my $query =
381             "SELECT distinct($column) as availablevalues FROM $table";
382             my $sth = $dbh->prepare($query);
383             $sth->execute();
384             my @values;
385             # push the runtime choosing option
386             my $list;
387             $list='branches' if $column eq 'branchcode' or $column eq 'holdingbranch' or $column eq 'homebranch';
388             $list='categorycode' if $column eq 'categorycode';
389             $list='itemtypes' if $column eq 'itype';
390             $list='ccode' if $column eq 'ccode';
391             # TODO : improve to let the librarian choose the description at runtime
392             push @values, {
393                 availablevalues => "<<$column" . ( $list ? "|$list" : '' ) . ">>",
394                 display_value   => "<<$column" . ( $list ? "|$list" : '' ) . ">>",
395             };
396             while ( my $row = $sth->fetchrow_hashref() ) {
397                 if ($row->{'availablevalues'} eq '') { $row->{'default'} = 1 }
398                 else { $row->{display_value} = _get_display_value( $row->{'availablevalues'}, $column ); }
399                 push @values, $row;
400             }
401             $sth->finish();
402
403             my %temp;
404             $temp{'name'}        = $value;
405             $temp{'description'} = $column_defs->{$value};
406             $temp{'values'}      = \@values;
407
408             push @criteria_array, \%temp;
409         }
410     }
411     return ( \@criteria_array );
412 }
413
414 sub nb_rows {
415     my $sql = shift or return;
416     my $sth = C4::Context->dbh->prepare($sql);
417     $sth->execute();
418     my $rows = $sth->fetchall_arrayref();
419     return scalar (@$rows);
420 }
421
422 =head2 execute_query
423
424   ($sth, $error) = execute_query($sql, $offset, $limit[, \@sql_params])
425
426
427 This function returns a DBI statement handler from which the caller can
428 fetch the results of the SQL passed via C<$sql>.
429
430 If passed any query other than a SELECT, or if there is a DB error,
431 C<$errors> is returned, and is a hashref containing the error after this
432 manner:
433
434 C<$error->{'sqlerr'}> contains the offending SQL keyword.
435 C<$error->{'queryerr'}> contains the native db engine error returned
436 for the query.
437
438 C<$offset>, and C<$limit> are required parameters.
439
440 C<\@sql_params> is an optional list of parameter values to paste in.
441 The caller is responsible for making sure that C<$sql> has placeholders
442 and that the number placeholders matches the number of parameters.
443
444 =cut
445
446 # returns $sql, $offset, $limit
447 # $sql returned will be transformed to:
448 #  ~ remove any LIMIT clause
449 #  ~ repace SELECT clause w/ SELECT count(*)
450
451 sub select_2_select_count {
452     # Modify the query passed in to create a count query... (I think this covers all cases -crn)
453     my ($sql) = strip_limit(shift) or return;
454     $sql =~ s/\bSELECT\W+(?:\w+\W+){1,}?FROM\b|\bSELECT\W\*\WFROM\b/SELECT count(*) FROM /ig;
455     return $sql;
456 }
457
458 # This removes the LIMIT from the query so that a custom one can be specified.
459 # Usage:
460 #   ($new_sql, $offset, $limit) = strip_limit($sql);
461 #
462 # Where:
463 #   $sql is the query to modify
464 #   $new_sql is the resulting query
465 #   $offset is the offset value, if the LIMIT was the two-argument form,
466 #       0 if it wasn't otherwise given.
467 #   $limit is the limit value
468 #
469 # Notes:
470 #   * This makes an effort to not break subqueries that have their own
471 #     LIMIT specified. It does that by only removing a LIMIT if it comes after
472 #     a WHERE clause (which isn't perfect, but at least should make more cases
473 #     work - subqueries with a limit in the WHERE will still break.)
474 #   * If your query doesn't have a WHERE clause then all LIMITs will be
475 #     removed. This may break some subqueries, but is hopefully rare enough
476 #     to not be a big issue.
477 sub strip_limit {
478     my ($sql) = @_;
479
480     return unless $sql;
481     return ($sql, 0, undef) unless $sql =~ /\bLIMIT\b/i;
482
483     # Two options: if there's no WHERE clause in the SQL, we simply capture
484     # any LIMIT that's there. If there is a WHERE, we make sure that we only
485     # capture a LIMIT after the last one. This prevents stomping on subqueries.
486     if ($sql !~ /\bWHERE\b/i) {
487         (my $res = $sql) =~ s/\bLIMIT\b\s*(\d+)(\s*\,\s*(\d+))?\s*/ /ig;
488         return ($res, (defined $2 ? $1 : 0), (defined $3 ? $3 : $1));
489     } else {
490         my $res = $sql;
491         $res =~ m/.*\bWHERE\b/gsi;
492         $res =~ s/\G(.*)\bLIMIT\b\s*(\d+)(\s*\,\s*(\d+))?\s*/$1 /is;
493         return ($res, (defined $3 ? $2 : 0), (defined $4 ? $4 : $2));
494     }
495 }
496
497 sub execute_query {
498
499     my ( $sql, $offset, $limit, $sql_params ) = @_;
500
501     $sql_params = [] unless defined $sql_params;
502
503     # check parameters
504     unless ($sql) {
505         carp "execute_query() called without SQL argument";
506         return;
507     }
508     $offset = 0    unless $offset;
509     $limit  = 999999 unless $limit;
510     $debug and print STDERR "execute_query($sql, $offset, $limit)\n";
511     if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
512         return (undef, {  sqlerr => $1} );
513     } elsif ($sql !~ /^\s*SELECT\b\s*/i) {
514         return (undef, { queryerr => 'Missing SELECT'} );
515     }
516
517     my ($useroffset, $userlimit);
518
519     # Grab offset/limit from user supplied LIMIT and drop the LIMIT so we can control pagination
520     ($sql, $useroffset, $userlimit) = strip_limit($sql);
521     $debug and warn sprintf "User has supplied (OFFSET,) LIMIT = %s, %s",
522         $useroffset,
523         (defined($userlimit ) ? $userlimit  : 'UNDEF');
524     $offset += $useroffset;
525     if (defined($userlimit)) {
526         if ($offset + $limit > $userlimit ) {
527             $limit = $userlimit - $offset;
528         } elsif ( ! $offset && $limit < $userlimit ) {
529             $limit = $userlimit;
530         }
531     }
532     $sql .= " LIMIT ?, ?";
533
534     my $sth = C4::Context->dbh->prepare($sql);
535     $sth->execute(@$sql_params, $offset, $limit);
536     return ( $sth, { queryerr => $sth->errstr } ) if ($sth->err);
537     return ( $sth );
538 }
539
540 =head2 save_report($sql,$name,$type,$notes)
541
542 Given some sql and a name this will saved it so that it can reused
543 Returns id of the newly created report
544
545 =cut
546
547 sub save_report {
548     my ($fields) = @_;
549     my $borrowernumber = $fields->{borrowernumber};
550     my $sql = $fields->{sql};
551     my $name = $fields->{name};
552     my $type = $fields->{type};
553     my $notes = $fields->{notes};
554     my $area = $fields->{area};
555     my $group = $fields->{group};
556     my $subgroup = $fields->{subgroup};
557     my $cache_expiry = $fields->{cache_expiry} || 300;
558     my $public = $fields->{public};
559
560     my $dbh = C4::Context->dbh();
561     $sql =~ s/(\s*\;\s*)$//;    # removes trailing whitespace and /;/
562     my $query = "INSERT INTO saved_sql (borrowernumber,date_created,last_modified,savedsql,report_name,report_area,report_group,report_subgroup,type,notes,cache_expiry,public)  VALUES (?,now(),now(),?,?,?,?,?,?,?,?,?)";
563     $dbh->do($query, undef, $borrowernumber, $sql, $name, $area, $group, $subgroup, $type, $notes, $cache_expiry, $public);
564
565     my $id = $dbh->selectrow_array("SELECT max(id) FROM saved_sql WHERE borrowernumber=? AND report_name=?", undef,
566                                    $borrowernumber, $name);
567     return $id;
568 }
569
570 sub update_sql {
571     my $id         = shift || croak "No Id given";
572     my $fields     = shift;
573     my $sql = $fields->{sql};
574     my $name = $fields->{name};
575     my $notes = $fields->{notes};
576     my $group = $fields->{group};
577     my $subgroup = $fields->{subgroup};
578     my $cache_expiry = $fields->{cache_expiry};
579     my $public = $fields->{public};
580
581     if( $cache_expiry >= 2592000 ){
582       die "Please specify a cache expiry less than 30 days\n";
583     }
584
585     my $dbh        = C4::Context->dbh();
586     $sql =~ s/(\s*\;\s*)$//;    # removes trailing whitespace and /;/
587     my $query = "UPDATE saved_sql SET savedsql = ?, last_modified = now(), report_name = ?, report_group = ?, report_subgroup = ?, notes = ?, cache_expiry = ?, public = ? WHERE id = ? ";
588     $dbh->do($query, undef, $sql, $name, $group, $subgroup, $notes, $cache_expiry, $public, $id );
589 }
590
591 sub store_results {
592     my ( $id, $json ) = @_;
593     my $dbh = C4::Context->dbh();
594     $dbh->do(q|
595         INSERT INTO saved_reports ( report_id, report, date_run ) VALUES ( ?, ?, NOW() );
596     |, undef, $id, $json );
597 }
598
599 sub format_results {
600     my ( $id ) = @_;
601     my $dbh = C4::Context->dbh();
602     my ( $report_name, $notes, $json, $date_run ) = $dbh->selectrow_array(q|
603        SELECT ss.report_name, ss.notes, sr.report, sr.date_run
604        FROM saved_sql ss
605        LEFT JOIN saved_reports sr ON sr.report_id = ss.id
606        WHERE sr.id = ?
607     |, undef, $id);
608     return {
609         report_name => $report_name,
610         notes => $notes,
611         results => from_json( $json ),
612         date_run => $date_run,
613     };
614 }
615
616 sub delete_report {
617     my (@ids) = @_;
618     return unless @ids;
619     foreach my $id (@ids) {
620         my $data = get_saved_report($id);
621         logaction( "REPORTS", "DELETE", $id, "$data->{'report_name'} | $data->{'savedsql'}  " ) if C4::Context->preference("ReportsLog");
622     }
623     my $dbh = C4::Context->dbh;
624     my $query = 'DELETE FROM saved_sql WHERE id IN (' . join( ',', ('?') x @ids ) . ')';
625     my $sth = $dbh->prepare($query);
626     return $sth->execute(@ids);
627 }
628
629 sub get_saved_reports_base_query {
630     my $area_name_sql_snippet = get_area_name_sql_snippet;
631     return <<EOQ;
632 SELECT s.*, $area_name_sql_snippet, av_g.lib AS groupname, av_sg.lib AS subgroupname,
633 b.firstname AS borrowerfirstname, b.surname AS borrowersurname
634 FROM saved_sql s
635 LEFT OUTER JOIN authorised_values av_g ON (av_g.category = 'REPORT_GROUP' AND av_g.authorised_value = s.report_group)
636 LEFT OUTER JOIN authorised_values av_sg ON (av_sg.category = 'REPORT_SUBGROUP' AND av_sg.lib_opac = s.report_group AND av_sg.authorised_value = s.report_subgroup)
637 LEFT OUTER JOIN borrowers b USING (borrowernumber)
638 EOQ
639 }
640
641 sub get_saved_reports {
642 # $filter is either { date => $d, author => $a, keyword => $kw, }
643 # or $keyword. Optional.
644     my ($filter) = @_;
645     $filter = { keyword => $filter } if $filter && !ref( $filter );
646     my ($group, $subgroup) = @_;
647
648     my $dbh   = C4::Context->dbh();
649     my $query = get_saved_reports_base_query;
650     my (@cond,@args);
651     if ($filter) {
652         if (my $date = $filter->{date}) {
653             $date = eval { output_pref( { dt => dt_from_string( $date ), dateonly => 1, dateformat => 'iso' }); };
654             push @cond, "DATE(last_modified) = ? OR
655                          DATE(last_run) = ?";
656             push @args, $date, $date, $date;
657         }
658         if (my $author = $filter->{author}) {
659             $author = "%$author%";
660             push @cond, "surname LIKE ? OR
661                          firstname LIKE ?";
662             push @args, $author, $author;
663         }
664         if (my $keyword = $filter->{keyword}) {
665             push @cond, q|
666                        report LIKE ?
667                     OR report_name LIKE ?
668                     OR notes LIKE ?
669                     OR savedsql LIKE ?
670                     OR s.id = ?
671             |;
672             push @args, "%$keyword%", "%$keyword%", "%$keyword%", "%$keyword%", $keyword;
673         }
674         if ($filter->{group}) {
675             push @cond, "report_group = ?";
676             push @args, $filter->{group};
677         }
678         if ($filter->{subgroup}) {
679             push @cond, "report_subgroup = ?";
680             push @args, $filter->{subgroup};
681         }
682     }
683     $query .= " WHERE ".join( " AND ", map "($_)", @cond ) if @cond;
684     $query .= " ORDER by date_created";
685     
686     my $result = $dbh->selectall_arrayref($query, {Slice => {}}, @args);
687
688     return $result;
689 }
690
691 sub get_saved_report {
692     my $dbh   = C4::Context->dbh();
693     my $query;
694     my $report_arg;
695     if ($#_ == 0 && ref $_[0] ne 'HASH') {
696         ($report_arg) = @_;
697         $query = " SELECT * FROM saved_sql WHERE id = ?";
698     } elsif (ref $_[0] eq 'HASH') {
699         my ($selector) = @_;
700         if ($selector->{name}) {
701             $query = " SELECT * FROM saved_sql WHERE report_name = ?";
702             $report_arg = $selector->{name};
703         } elsif ($selector->{id} || $selector->{id} eq '0') {
704             $query = " SELECT * FROM saved_sql WHERE id = ?";
705             $report_arg = $selector->{id};
706         } else {
707             return;
708         }
709     } else {
710         return;
711     }
712     return $dbh->selectrow_hashref($query, undef, $report_arg);
713 }
714
715 =head2 create_compound($masterID,$subreportID)
716
717 This will take 2 reports and create a compound report using both of them
718
719 =cut
720
721 sub create_compound {
722     my ( $masterID, $subreportID ) = @_;
723     my $dbh = C4::Context->dbh();
724
725     # get the reports
726     my $master = get_saved_report($masterID);
727     my $mastersql = $master->{savedsql};
728     my $mastertype = $master->{type};
729     my $sub = get_saved_report($subreportID);
730     my $subsql = $master->{savedsql};
731     my $subtype = $master->{type};
732
733     # now we have to do some checking to see how these two will fit together
734     # or if they will
735     my ( $mastertables, $subtables );
736     if ( $mastersql =~ / from (.*) where /i ) {
737         $mastertables = $1;
738     }
739     if ( $subsql =~ / from (.*) where /i ) {
740         $subtables = $1;
741     }
742     return ( $mastertables, $subtables );
743 }
744
745 =head2 get_column_type($column)
746
747 This takes a column name of the format table.column and will return what type it is
748 (free text, set values, date)
749
750 =cut
751
752 sub get_column_type {
753         my ($tablecolumn) = @_;
754         my ($table,$column) = split(/\./,$tablecolumn);
755         my $dbh = C4::Context->dbh();
756         my $catalog;
757         my $schema;
758
759     # mysql doesn't support a column selection, set column to %
760         my $tempcolumn='%';
761         my $sth = $dbh->column_info( $catalog, $schema, $table, $tempcolumn ) || die $dbh->errstr;
762         while (my $info = $sth->fetchrow_hashref()){
763                 if ($info->{'COLUMN_NAME'} eq $column){
764                         #column we want
765                         if ($info->{'TYPE_NAME'} eq 'CHAR' || $info->{'TYPE_NAME'} eq 'VARCHAR'){
766                                 $info->{'TYPE_NAME'} = 'distinct';
767                         }
768                         return $info->{'TYPE_NAME'};            
769                 }
770         }
771 }
772
773 =head2 get_distinct_values($column)
774
775 Given a column name, return an arrary ref of hashrefs suitable for use as a tmpl_loop 
776 with the distinct values of the column
777
778 =cut
779
780 sub get_distinct_values {
781         my ($tablecolumn) = @_;
782         my ($table,$column) = split(/\./,$tablecolumn);
783         my $dbh = C4::Context->dbh();
784         my $query =
785           "SELECT distinct($column) as availablevalues FROM $table";
786         my $sth = $dbh->prepare($query);
787         $sth->execute();
788     return $sth->fetchall_arrayref({});
789 }       
790
791 sub save_dictionary {
792     my ( $name, $description, $sql, $area ) = @_;
793     my $dbh   = C4::Context->dbh();
794     my $query = "INSERT INTO reports_dictionary (name,description,saved_sql,report_area,date_created,date_modified)
795   VALUES (?,?,?,?,now(),now())";
796     my $sth = $dbh->prepare($query);
797     $sth->execute($name,$description,$sql,$area) || return 0;
798     return 1;
799 }
800
801 sub get_from_dictionary {
802     my ( $area, $id ) = @_;
803     my $dbh   = C4::Context->dbh();
804     my $area_name_sql_snippet = get_area_name_sql_snippet;
805     my $query = <<EOQ;
806 SELECT d.*, $area_name_sql_snippet
807 FROM reports_dictionary d
808 EOQ
809
810     if ($area) {
811         $query .= " WHERE report_area = ?";
812     } elsif ($id) {
813         $query .= " WHERE id = ?";
814     }
815     my $sth = $dbh->prepare($query);
816     if ($id) {
817         $sth->execute($id);
818     } elsif ($area) {
819         $sth->execute($area);
820     } else {
821         $sth->execute();
822     }
823     my @loop;
824     while ( my $data = $sth->fetchrow_hashref() ) {
825         push @loop, $data;
826     }
827     return ( \@loop );
828 }
829
830 sub delete_definition {
831         my ($id) = @_ or return;
832         my $dbh = C4::Context->dbh();
833         my $query = "DELETE FROM reports_dictionary WHERE id = ?";
834         my $sth = $dbh->prepare($query);
835         $sth->execute($id);
836 }
837
838 sub get_sql {
839         my ($id) = @_ or return;
840         my $dbh = C4::Context->dbh();
841         my $query = "SELECT * FROM saved_sql WHERE id = ?";
842         my $sth = $dbh->prepare($query);
843         $sth->execute($id);
844         my $data=$sth->fetchrow_hashref();
845         return $data->{'savedsql'};
846 }
847
848 sub get_results {
849     my ( $report_id ) = @_;
850     my $dbh = C4::Context->dbh;
851     warn $report_id;
852     return $dbh->selectall_arrayref(q|
853         SELECT id, report, date_run
854         FROM saved_reports
855         WHERE report_id = ?
856     |, { Slice => {} }, $report_id);
857 }
858
859 sub _get_column_defs {
860     my ($cgi) = @_;
861     my %columns;
862     my $columns_def_file = "columns.def";
863     my $htdocs = C4::Context->config('intrahtdocs');
864     my $section = 'intranet';
865
866     # We need the theme and the lang
867     # Since columns.def is not in the modules directory, we cannot sent it for the $tmpl var
868     my ($theme, $lang, $availablethemes) = C4::Templates::themelanguage($htdocs, 'about.tt', $section, $cgi);
869
870     my $full_path_to_columns_def_file="$htdocs/$theme/$lang/$columns_def_file";
871     open (my $fh, '<:encoding(utf-8)', $full_path_to_columns_def_file);
872     while ( my $input = <$fh> ){
873         chomp $input;
874         if ( $input =~ m|<field name="(.*)">(.*)</field>| ) {
875             my ( $field, $translation ) = ( $1, $2 );
876             $columns{$field} = $translation;
877         }
878     }
879     close $fh;
880     return \%columns;
881 }
882
883 =head2 GetReservedAuthorisedValues
884
885     my %reserved_authorised_values = GetReservedAuthorisedValues();
886
887 Returns a hash containig all reserved words
888
889 =cut
890
891 sub GetReservedAuthorisedValues {
892     my %reserved_authorised_values =
893             map { $_ => 1 } ( 'date',
894                               'branches',
895                               'itemtypes',
896                               'cn_source',
897                               'categorycode',
898                               'biblio_framework' );
899
900    return \%reserved_authorised_values;
901 }
902
903
904 =head2 IsAuthorisedValueValid
905
906     my $is_valid_ath_value = IsAuthorisedValueValid($authorised_value)
907
908 Returns 1 if $authorised_value is on the reserved authorised values list or
909 in the authorised value categories defined in
910
911 =cut
912
913 sub IsAuthorisedValueValid {
914
915     my $authorised_value = shift;
916     my $reserved_authorised_values = GetReservedAuthorisedValues();
917
918     if ( exists $reserved_authorised_values->{$authorised_value} ||
919          Koha::AuthorisedValues->search({ category => $authorised_value })->count ) {
920         return 1;
921     }
922
923     return 0;
924 }
925
926 =head2 GetParametersFromSQL
927
928     my @sql_parameters = GetParametersFromSQL($sql)
929
930 Returns an arrayref of hashes containing the keys name and authval
931
932 =cut
933
934 sub GetParametersFromSQL {
935
936     my $sql = shift ;
937     my @split = split(/<<|>>/,$sql);
938     my @sql_parameters = ();
939
940     for ( my $i = 0; $i < ($#split/2) ; $i++ ) {
941         my ($name,$authval) = split(/\|/,$split[$i*2+1]);
942         push @sql_parameters, { 'name' => $name, 'authval' => $authval };
943     }
944
945     return \@sql_parameters;
946 }
947
948 =head2 ValidateSQLParameters
949
950     my @problematic_parameters = ValidateSQLParameters($sql)
951
952 Returns an arrayref of hashes containing the keys name and authval of
953 those SQL parameters that do not correspond to valid authorised names
954
955 =cut
956
957 sub ValidateSQLParameters {
958
959     my $sql = shift;
960     my @problematic_parameters = ();
961     my $sql_parameters = GetParametersFromSQL($sql);
962
963     foreach my $sql_parameter (@$sql_parameters) {
964         if ( defined $sql_parameter->{'authval'} ) {
965             push @problematic_parameters, $sql_parameter unless
966                 IsAuthorisedValueValid($sql_parameter->{'authval'});
967         }
968     }
969
970     return \@problematic_parameters;
971 }
972
973 sub _get_display_value {
974     my ( $original_value, $column ) = @_;
975     if ( $column eq 'periodicity' ) {
976         my $dbh = C4::Context->dbh();
977         my $query = "SELECT description FROM subscription_frequencies WHERE id = ?";
978         my $sth   = $dbh->prepare($query);
979         $sth->execute($original_value);
980         return $sth->fetchrow;
981     }
982     return $original_value;
983 }
984
985 1;
986 __END__
987
988 =head1 AUTHOR
989
990 Chris Cormack <crc@liblime.com>
991
992 =cut