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