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