Bug 9915: (follow-up) use SQL placeholders
[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 );
516     # my @xmlarray = ... ;
517     # my $url = "/cgi-bin/koha/reports/guided_reports.pl?phase=retrieve%20results&id=$id";
518     # my $xml = XML::Dumper->new()->pl2xml( \@xmlarray );
519     # store_results($id,$xml);
520 }
521
522 =head2 save_report($sql,$name,$type,$notes)
523
524 Given some sql and a name this will saved it so that it can reused
525 Returns id of the newly created report
526
527 =cut
528
529 sub save_report {
530     my ($fields) = @_;
531     my $borrowernumber = $fields->{borrowernumber};
532     my $sql = $fields->{sql};
533     my $name = $fields->{name};
534     my $type = $fields->{type};
535     my $notes = $fields->{notes};
536     my $area = $fields->{area};
537     my $group = $fields->{group};
538     my $subgroup = $fields->{subgroup};
539     my $cache_expiry = $fields->{cache_expiry} || 300;
540     my $public = $fields->{public};
541
542     my $dbh = C4::Context->dbh();
543     $sql =~ s/(\s*\;\s*)$//;    # removes trailing whitespace and /;/
544     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(),?,?,?,?,?,?,?,?,?)";
545     $dbh->do($query, undef, $borrowernumber, $sql, $name, $area, $group, $subgroup, $type, $notes, $cache_expiry, $public);
546
547     my $id = $dbh->selectrow_array("SELECT max(id) FROM saved_sql WHERE borrowernumber=? AND report_name=?", undef,
548                                    $borrowernumber, $name);
549     return $id;
550 }
551
552 sub update_sql {
553     my $id         = shift || croak "No Id given";
554     my $fields     = shift;
555     my $sql = $fields->{sql};
556     my $name = $fields->{name};
557     my $notes = $fields->{notes};
558     my $group = $fields->{group};
559     my $subgroup = $fields->{subgroup};
560     my $cache_expiry = $fields->{cache_expiry};
561     my $public = $fields->{public};
562
563     if( $cache_expiry >= 2592000 ){
564       die "Please specify a cache expiry less than 30 days\n";
565     }
566
567     my $dbh        = C4::Context->dbh();
568     $sql =~ s/(\s*\;\s*)$//;    # removes trailing whitespace and /;/
569     my $query = "UPDATE saved_sql SET savedsql = ?, last_modified = now(), report_name = ?, report_group = ?, report_subgroup = ?, notes = ?, cache_expiry = ?, public = ? WHERE id = ? ";
570     $dbh->do($query, undef, $sql, $name, $group, $subgroup, $notes, $cache_expiry, $public, $id );
571 }
572
573 sub store_results {
574         my ($id,$xml)=@_;
575         my $dbh = C4::Context->dbh();
576         my $query = "SELECT * FROM saved_reports WHERE report_id=?";
577         my $sth = $dbh->prepare($query);
578         $sth->execute($id);
579         if (my $data=$sth->fetchrow_hashref()){
580                 my $query2 = "UPDATE saved_reports SET report=?,date_run=now() WHERE report_id=?";
581                 my $sth2 = $dbh->prepare($query2);
582             $sth2->execute($xml,$id);
583         }
584         else {
585                 my $query2 = "INSERT INTO saved_reports (report_id,report,date_run) VALUES (?,?,now())";
586                 my $sth2 = $dbh->prepare($query2);
587                 $sth2->execute($id,$xml);
588         }
589 }
590
591 sub format_results {
592         my ($id) = @_;
593         my $dbh = C4::Context->dbh();
594         my $query = "SELECT * FROM saved_reports WHERE report_id = ?";
595         my $sth = $dbh->prepare($query);
596         $sth->execute($id);
597         my $data = $sth->fetchrow_hashref();
598         my $dump = new XML::Dumper;
599         my $perl = $dump->xml2pl( $data->{'report'} );
600         foreach my $row (@$perl) {
601                 my $htmlrow="<tr>";
602                 foreach my $key (keys %$row){
603                         $htmlrow .= "<td>$row->{$key}</td>";
604                 }
605                 $htmlrow .= "</tr>";
606                 $row->{'row'} = $htmlrow;
607         }
608         $sth->finish;
609         $query = "SELECT * FROM saved_sql WHERE id = ?";
610         $sth = $dbh->prepare($query);
611         $sth->execute($id);
612         $data = $sth->fetchrow_hashref();
613         return ($perl,$data->{'report_name'},$data->{'notes'}); 
614 }       
615
616 sub delete_report {
617     my (@ids) = @_;
618     return unless @ids;
619     my $dbh = C4::Context->dbh;
620     my $query = 'DELETE FROM saved_sql WHERE id IN (' . join( ',', ('?') x @ids ) . ')';
621     my $sth = $dbh->prepare($query);
622     return $sth->execute(@ids);
623 }
624
625 my $SAVED_REPORTS_BASE_QRY = <<EOQ;
626 SELECT s.*, r.report, r.date_run, $AREA_NAME_SQL_SNIPPET, av_g.lib AS groupname, av_sg.lib AS subgroupname,
627 b.firstname AS borrowerfirstname, b.surname AS borrowersurname
628 FROM saved_sql s
629 LEFT JOIN saved_reports r ON r.report_id = s.id
630 LEFT OUTER JOIN authorised_values av_g ON (av_g.category = 'REPORT_GROUP' AND av_g.authorised_value = s.report_group)
631 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)
632 LEFT OUTER JOIN borrowers b USING (borrowernumber)
633 EOQ
634 my $DATE_FORMAT = "%d/%m/%Y";
635 sub get_saved_reports {
636 # $filter is either { date => $d, author => $a, keyword => $kw, }
637 # or $keyword. Optional.
638     my ($filter) = @_;
639     $filter = { keyword => $filter } if $filter && !ref( $filter );
640     my ($group, $subgroup) = @_;
641
642     my $dbh   = C4::Context->dbh();
643     my $query = $SAVED_REPORTS_BASE_QRY;
644     my (@cond,@args);
645     if ($filter) {
646         if (my $date = $filter->{date}) {
647             $date = format_date_in_iso($date);
648             push @cond, "DATE(date_run) = ? OR
649                          DATE(date_created) = ? OR
650                          DATE(last_modified) = ? OR
651                          DATE(last_run) = ?";
652             push @args, $date, $date, $date, $date;
653         }
654         if (my $author = $filter->{author}) {
655             $author = "%$author%";
656             push @cond, "surname LIKE ? OR
657                          firstname LIKE ?";
658             push @args, $author, $author;
659         }
660         if (my $keyword = $filter->{keyword}) {
661             $keyword = "%$keyword%";
662             push @cond, "report LIKE ? OR
663                          report_name LIKE ? OR
664                          notes LIKE ? OR
665                          savedsql LIKE ?";
666             push @args, $keyword, $keyword, $keyword, $keyword;
667         }
668         if ($filter->{group}) {
669             push @cond, "report_group = ?";
670             push @args, $filter->{group};
671         }
672         if ($filter->{subgroup}) {
673             push @cond, "report_subgroup = ?";
674             push @args, $filter->{subgroup};
675         }
676     }
677     $query .= " WHERE ".join( " AND ", map "($_)", @cond ) if @cond;
678     $query .= " ORDER by date_created";
679     
680     my $result = $dbh->selectall_arrayref($query, {Slice => {}}, @args);
681
682     return $result;
683 }
684
685 sub get_saved_report {
686     my $dbh   = C4::Context->dbh();
687     my $query;
688     my $report_arg;
689     if ($#_ == 0 && ref $_[0] ne 'HASH') {
690         ($report_arg) = @_;
691         $query = " SELECT * FROM saved_sql WHERE id = ?";
692     } elsif (ref $_[0] eq 'HASH') {
693         my ($selector) = @_;
694         if ($selector->{name}) {
695             $query = " SELECT * FROM saved_sql WHERE report_name = ?";
696             $report_arg = $selector->{name};
697         } elsif ($selector->{id} || $selector->{id} eq '0') {
698             $query = " SELECT * FROM saved_sql WHERE id = ?";
699             $report_arg = $selector->{id};
700         } else {
701             return;
702         }
703     } else {
704         return;
705     }
706     return $dbh->selectrow_hashref($query, undef, $report_arg);
707 }
708
709 =head2 create_compound($masterID,$subreportID)
710
711 This will take 2 reports and create a compound report using both of them
712
713 =cut
714
715 sub create_compound {
716     my ( $masterID, $subreportID ) = @_;
717     my $dbh = C4::Context->dbh();
718
719     # get the reports
720     my $master = get_saved_report($masterID);
721     my $mastersql = $master->{savedsql};
722     my $mastertype = $master->{type};
723     my $sub = get_saved_report($subreportID);
724     my $subsql = $master->{savedsql};
725     my $subtype = $master->{type};
726
727     # now we have to do some checking to see how these two will fit together
728     # or if they will
729     my ( $mastertables, $subtables );
730     if ( $mastersql =~ / from (.*) where /i ) {
731         $mastertables = $1;
732     }
733     if ( $subsql =~ / from (.*) where /i ) {
734         $subtables = $1;
735     }
736     return ( $mastertables, $subtables );
737 }
738
739 =head2 get_column_type($column)
740
741 This takes a column name of the format table.column and will return what type it is
742 (free text, set values, date)
743
744 =cut
745
746 sub get_column_type {
747         my ($tablecolumn) = @_;
748         my ($table,$column) = split(/\./,$tablecolumn);
749         my $dbh = C4::Context->dbh();
750         my $catalog;
751         my $schema;
752
753         # mysql doesnt support a column selection, set column to %
754         my $tempcolumn='%';
755         my $sth = $dbh->column_info( $catalog, $schema, $table, $tempcolumn ) || die $dbh->errstr;
756         while (my $info = $sth->fetchrow_hashref()){
757                 if ($info->{'COLUMN_NAME'} eq $column){
758                         #column we want
759                         if ($info->{'TYPE_NAME'} eq 'CHAR' || $info->{'TYPE_NAME'} eq 'VARCHAR'){
760                                 $info->{'TYPE_NAME'} = 'distinct';
761                         }
762                         return $info->{'TYPE_NAME'};            
763                 }
764         }
765 }
766
767 =head2 get_distinct_values($column)
768
769 Given a column name, return an arrary ref of hashrefs suitable for use as a tmpl_loop 
770 with the distinct values of the column
771
772 =cut
773
774 sub get_distinct_values {
775         my ($tablecolumn) = @_;
776         my ($table,$column) = split(/\./,$tablecolumn);
777         my $dbh = C4::Context->dbh();
778         my $query =
779           "SELECT distinct($column) as availablevalues FROM $table";
780         my $sth = $dbh->prepare($query);
781         $sth->execute();
782     return $sth->fetchall_arrayref({});
783 }       
784
785 sub save_dictionary {
786     my ( $name, $description, $sql, $area ) = @_;
787     my $dbh   = C4::Context->dbh();
788     my $query = "INSERT INTO reports_dictionary (name,description,saved_sql,report_area,date_created,date_modified)
789   VALUES (?,?,?,?,now(),now())";
790     my $sth = $dbh->prepare($query);
791     $sth->execute($name,$description,$sql,$area) || return 0;
792     return 1;
793 }
794
795 my $DICTIONARY_BASE_QRY = <<EOQ;
796 SELECT d.*, $AREA_NAME_SQL_SNIPPET
797 FROM reports_dictionary d
798 EOQ
799 sub get_from_dictionary {
800     my ( $area, $id ) = @_;
801     my $dbh   = C4::Context->dbh();
802     my $query = $DICTIONARY_BASE_QRY;
803     if ($area) {
804         $query .= " WHERE report_area = ?";
805     } elsif ($id) {
806         $query .= " WHERE id = ?";
807     }
808     my $sth = $dbh->prepare($query);
809     if ($id) {
810         $sth->execute($id);
811     } elsif ($area) {
812         $sth->execute($area);
813     } else {
814         $sth->execute();
815     }
816     my @loop;
817     while ( my $data = $sth->fetchrow_hashref() ) {
818         push @loop, $data;
819     }
820     return ( \@loop );
821 }
822
823 sub delete_definition {
824         my ($id) = @_ or return;
825         my $dbh = C4::Context->dbh();
826         my $query = "DELETE FROM reports_dictionary WHERE id = ?";
827         my $sth = $dbh->prepare($query);
828         $sth->execute($id);
829 }
830
831 sub get_sql {
832         my ($id) = @_ or return;
833         my $dbh = C4::Context->dbh();
834         my $query = "SELECT * FROM saved_sql WHERE id = ?";
835         my $sth = $dbh->prepare($query);
836         $sth->execute($id);
837         my $data=$sth->fetchrow_hashref();
838         return $data->{'savedsql'};
839 }
840
841 sub _get_column_defs {
842     my ($cgi) = @_;
843     my %columns;
844     my $columns_def_file = "columns.def";
845     my $htdocs = C4::Context->config('intrahtdocs');
846     my $section = 'intranet';
847
848     # We need the theme and the lang
849     # Since columns.def is not in the modules directory, we cannot sent it for the $tmpl var
850     my ($theme, $lang, $availablethemes) = C4::Templates::themelanguage($htdocs, 'about.tt', $section, $cgi);
851
852     my $full_path_to_columns_def_file="$htdocs/$theme/$lang/$columns_def_file";
853     open (my $fh, $full_path_to_columns_def_file);
854     while ( my $input = <$fh> ){
855         chomp $input;
856         if ( $input =~ m|<field name="(.*)">(.*)</field>| ) {
857             my ( $field, $translation ) = ( $1, $2 );
858             $columns{$field} = $translation;
859         }
860     }
861     close $fh;
862     return \%columns;
863 }
864
865 =head2 build_authorised_value_list($authorised_value)
866
867 Returns an arrayref - hashref pair. The hashref consists of
868 various code => name lists depending on the $authorised_value.
869 The arrayref is the hashref keys, in appropriate order
870
871 =cut
872
873 sub build_authorised_value_list {
874     my ( $authorised_value ) = @_;
875
876     my $dbh = C4::Context->dbh;
877     my @authorised_values;
878     my %authorised_lib;
879
880     # builds list, depending on authorised value...
881     if ( $authorised_value eq "branches" ) {
882         my $branches = GetBranchesLoop();
883         foreach my $thisbranch (@$branches) {
884             push @authorised_values, $thisbranch->{value};
885             $authorised_lib{ $thisbranch->{value} } = $thisbranch->{branchname};
886         }
887     } elsif ( $authorised_value eq "itemtypes" ) {
888         my $sth = $dbh->prepare("SELECT itemtype,description FROM itemtypes ORDER BY description");
889         $sth->execute;
890         while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
891             push @authorised_values, $itemtype;
892             $authorised_lib{$itemtype} = $description;
893         }
894     } elsif ( $authorised_value eq "cn_source" ) {
895         my $class_sources  = GetClassSources();
896         my $default_source = C4::Context->preference("DefaultClassificationSource");
897         foreach my $class_source ( sort keys %$class_sources ) {
898             next
899               unless $class_sources->{$class_source}->{'used'}
900                   or ( $class_source eq $default_source );
901             push @authorised_values, $class_source;
902             $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
903         }
904     } elsif ( $authorised_value eq "categorycode" ) {
905         my $sth = $dbh->prepare("SELECT categorycode, description FROM categories ORDER BY description");
906         $sth->execute;
907         while ( my ( $categorycode, $description ) = $sth->fetchrow_array ) {
908             push @authorised_values, $categorycode;
909             $authorised_lib{$categorycode} = $description;
910         }
911
912         #---- "true" authorised value
913     } else {
914         my $authorised_values_sth = $dbh->prepare("SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib");
915
916         $authorised_values_sth->execute($authorised_value);
917
918         while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
919             push @authorised_values, $value;
920             $authorised_lib{$value} = $lib;
921
922             # For item location, we show the code and the libelle
923             $authorised_lib{$value} = $lib;
924         }
925     }
926
927     return (\@authorised_values, \%authorised_lib);
928 }
929
930 =head2 GetReservedAuthorisedValues
931
932     my %reserved_authorised_values = GetReservedAuthorisedValues();
933
934 Returns a hash containig all reserved words
935
936 =cut
937
938 sub GetReservedAuthorisedValues {
939     my %reserved_authorised_values =
940             map { $_ => 1 } ( 'date',
941                               'branches',
942                               'itemtypes',
943                               'cn_source',
944                               'categorycode' );
945
946    return \%reserved_authorised_values;
947 }
948
949
950 =head2 IsAuthorisedValueValid
951
952     my $is_valid_ath_value = IsAuthorisedValueValid($authorised_value)
953
954 Returns 1 if $authorised_value is on the reserved authorised values list or
955 in the authorised value categories defined in
956
957 =cut
958
959 sub IsAuthorisedValueValid {
960
961     my $authorised_value = shift;
962     my $reserved_authorised_values = GetReservedAuthorisedValues();
963
964     if ( exists $reserved_authorised_values->{$authorised_value} ||
965          IsAuthorisedValueCategory($authorised_value)   ) {
966         return 1;
967     }
968
969     return 0;
970 }
971
972 =head2 GetParametersFromSQL
973
974     my @sql_parameters = GetParametersFromSQL($sql)
975
976 Returns an arrayref of hashes containing the keys name and authval
977
978 =cut
979
980 sub GetParametersFromSQL {
981
982     my $sql = shift ;
983     my @split = split(/<<|>>/,$sql);
984     my @sql_parameters = ();
985
986     for ( my $i = 0; $i < ($#split/2) ; $i++ ) {
987         my ($name,$authval) = split(/\|/,$split[$i*2+1]);
988         push @sql_parameters, { 'name' => $name, 'authval' => $authval };
989     }
990
991     return \@sql_parameters;
992 }
993
994 =head2 ValidateSQLParameters
995
996     my @problematic_parameters = ValidateSQLParameters($sql)
997
998 Returns an arrayref of hashes containing the keys name and authval of
999 those SQL parameters that do not correspond to valid authorised names
1000
1001 =cut
1002
1003 sub ValidateSQLParameters {
1004
1005     my $sql = shift;
1006     my @problematic_parameters = ();
1007     my $sql_parameters = GetParametersFromSQL($sql);
1008
1009     foreach my $sql_parameter (@$sql_parameters) {
1010         if ( defined $sql_parameter->{'authval'} ) {
1011             push @problematic_parameters, $sql_parameter unless
1012                 IsAuthorisedValueValid($sql_parameter->{'authval'});
1013         }
1014     }
1015
1016     return \@problematic_parameters;
1017 }
1018
1019 1;
1020 __END__
1021
1022 =head1 AUTHOR
1023
1024 Chris Cormack <crc@liblime.com>
1025
1026 =cut