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