c4d783f011620e9b0387b35f993297a70e6d73a2
[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 use JSON qw( from_json );
24
25 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
26 use C4::Context;
27 use C4::Templates qw/themelanguage/;
28 use C4::Koha;
29 use Koha::DateUtils;
30 use C4::Output;
31 use C4::Debug;
32 use C4::Log;
33
34 use Koha::AuthorisedValues;
35 use Koha::Patron::Categories;
36 use Koha::SharedContent;
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
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, $report_id ) = @_;
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 $dbh = C4::Context->dbh;
536
537     $dbh->do( 'UPDATE saved_sql SET last_run = NOW() WHERE id = ?', undef, $report_id ) if $report_id;
538
539     my $sth = $dbh->prepare($sql);
540     $sth->execute(@$sql_params, $offset, $limit);
541
542     return ( $sth, { queryerr => $sth->errstr } ) if ($sth->err);
543     return ( $sth );
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, $json ) = @_;
599     my $dbh = C4::Context->dbh();
600     $dbh->do(q|
601         INSERT INTO saved_reports ( report_id, report, date_run ) VALUES ( ?, ?, NOW() );
602     |, undef, $id, $json );
603 }
604
605 sub format_results {
606     my ( $id ) = @_;
607     my $dbh = C4::Context->dbh();
608     my ( $report_name, $notes, $json, $date_run ) = $dbh->selectrow_array(q|
609        SELECT ss.report_name, ss.notes, sr.report, sr.date_run
610        FROM saved_sql ss
611        LEFT JOIN saved_reports sr ON sr.report_id = ss.id
612        WHERE sr.id = ?
613     |, undef, $id);
614     return {
615         report_name => $report_name,
616         notes => $notes,
617         results => from_json( $json ),
618         date_run => $date_run,
619     };
620 }
621
622 sub delete_report {
623     my (@ids) = @_;
624     return unless @ids;
625     foreach my $id (@ids) {
626         my $data = Koha::Reports->find($id);
627         logaction( "REPORTS", "DELETE", $id, $data->report_name." | ".$data->savedsql ) if C4::Context->preference("ReportsLog");
628     }
629     my $dbh = C4::Context->dbh;
630     my $query = 'DELETE FROM saved_sql WHERE id IN (' . join( ',', ('?') x @ids ) . ')';
631     my $sth = $dbh->prepare($query);
632     return $sth->execute(@ids);
633 }
634
635 sub get_saved_reports_base_query {
636     my $area_name_sql_snippet = get_area_name_sql_snippet;
637     return <<EOQ;
638 SELECT s.*, $area_name_sql_snippet, av_g.lib AS groupname, av_sg.lib AS subgroupname,
639 b.firstname AS borrowerfirstname, b.surname AS borrowersurname
640 FROM saved_sql s
641 LEFT JOIN saved_reports r ON r.report_id = s.id
642 LEFT OUTER JOIN authorised_values av_g ON (av_g.category = 'REPORT_GROUP' AND av_g.authorised_value = s.report_group)
643 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)
644 LEFT OUTER JOIN borrowers b USING (borrowernumber)
645 EOQ
646 }
647
648 sub get_saved_reports {
649 # $filter is either { date => $d, author => $a, keyword => $kw, }
650 # or $keyword. Optional.
651     my ($filter) = @_;
652     $filter = { keyword => $filter } if $filter && !ref( $filter );
653     my ($group, $subgroup) = @_;
654
655     my $dbh   = C4::Context->dbh();
656     my $query = get_saved_reports_base_query;
657     my (@cond,@args);
658     if ($filter) {
659         if (my $date = $filter->{date}) {
660             $date = eval { output_pref( { dt => dt_from_string( $date ), dateonly => 1, dateformat => 'iso' }); };
661             push @cond, "DATE(last_modified) = ? OR
662                          DATE(last_run) = ?";
663             push @args, $date, $date, $date;
664         }
665         if (my $author = $filter->{author}) {
666             $author = "%$author%";
667             push @cond, "surname LIKE ? OR
668                          firstname LIKE ?";
669             push @args, $author, $author;
670         }
671         if (my $keyword = $filter->{keyword}) {
672             push @cond, q|
673                        report LIKE ?
674                     OR report_name LIKE ?
675                     OR notes LIKE ?
676                     OR savedsql LIKE ?
677                     OR s.id = ?
678             |;
679             push @args, "%$keyword%", "%$keyword%", "%$keyword%", "%$keyword%", $keyword;
680         }
681         if ($filter->{group}) {
682             push @cond, "report_group = ?";
683             push @args, $filter->{group};
684         }
685         if ($filter->{subgroup}) {
686             push @cond, "report_subgroup = ?";
687             push @args, $filter->{subgroup};
688         }
689     }
690     $query .= " WHERE ".join( " AND ", map "($_)", @cond ) if @cond;
691     $query .= " ORDER by date_created";
692     
693     my $result = $dbh->selectall_arrayref($query, {Slice => {}}, @args);
694
695     return $result;
696 }
697
698 =head2 get_column_type($column)
699
700 This takes a column name of the format table.column and will return what type it is
701 (free text, set values, date)
702
703 =cut
704
705 sub get_column_type {
706         my ($tablecolumn) = @_;
707         my ($table,$column) = split(/\./,$tablecolumn);
708         my $dbh = C4::Context->dbh();
709         my $catalog;
710         my $schema;
711
712     # mysql doesn't support a column selection, set column to %
713         my $tempcolumn='%';
714         my $sth = $dbh->column_info( $catalog, $schema, $table, $tempcolumn ) || die $dbh->errstr;
715         while (my $info = $sth->fetchrow_hashref()){
716                 if ($info->{'COLUMN_NAME'} eq $column){
717                         #column we want
718                         if ($info->{'TYPE_NAME'} eq 'CHAR' || $info->{'TYPE_NAME'} eq 'VARCHAR'){
719                                 $info->{'TYPE_NAME'} = 'distinct';
720                         }
721                         return $info->{'TYPE_NAME'};            
722                 }
723         }
724 }
725
726 =head2 get_distinct_values($column)
727
728 Given a column name, return an arrary ref of hashrefs suitable for use as a tmpl_loop 
729 with the distinct values of the column
730
731 =cut
732
733 sub get_distinct_values {
734         my ($tablecolumn) = @_;
735         my ($table,$column) = split(/\./,$tablecolumn);
736         my $dbh = C4::Context->dbh();
737         my $query =
738           "SELECT distinct($column) as availablevalues FROM $table";
739         my $sth = $dbh->prepare($query);
740         $sth->execute();
741     return $sth->fetchall_arrayref({});
742 }       
743
744 sub save_dictionary {
745     my ( $name, $description, $sql, $area ) = @_;
746     my $dbh   = C4::Context->dbh();
747     my $query = "INSERT INTO reports_dictionary (name,description,saved_sql,report_area,date_created,date_modified)
748   VALUES (?,?,?,?,now(),now())";
749     my $sth = $dbh->prepare($query);
750     $sth->execute($name,$description,$sql,$area) || return 0;
751     return 1;
752 }
753
754 sub get_from_dictionary {
755     my ( $area, $id ) = @_;
756     my $dbh   = C4::Context->dbh();
757     my $area_name_sql_snippet = get_area_name_sql_snippet;
758     my $query = <<EOQ;
759 SELECT d.*, $area_name_sql_snippet
760 FROM reports_dictionary d
761 EOQ
762
763     if ($area) {
764         $query .= " WHERE report_area = ?";
765     } elsif ($id) {
766         $query .= " WHERE id = ?";
767     }
768     my $sth = $dbh->prepare($query);
769     if ($id) {
770         $sth->execute($id);
771     } elsif ($area) {
772         $sth->execute($area);
773     } else {
774         $sth->execute();
775     }
776     my @loop;
777     while ( my $data = $sth->fetchrow_hashref() ) {
778         push @loop, $data;
779     }
780     return ( \@loop );
781 }
782
783 sub delete_definition {
784         my ($id) = @_ or return;
785         my $dbh = C4::Context->dbh();
786         my $query = "DELETE FROM reports_dictionary WHERE id = ?";
787         my $sth = $dbh->prepare($query);
788         $sth->execute($id);
789 }
790
791 =head2 get_sql($report_id)
792
793 Given a report id, return the SQL statement for that report.
794 Otherwise, it just returns.
795
796 =cut
797
798 sub get_sql {
799         my ($id) = @_ or return;
800         my $dbh = C4::Context->dbh();
801         my $query = "SELECT * FROM saved_sql WHERE id = ?";
802         my $sth = $dbh->prepare($query);
803         $sth->execute($id);
804         my $data=$sth->fetchrow_hashref();
805         return $data->{'savedsql'};
806 }
807
808 sub get_results {
809     my ( $report_id ) = @_;
810     my $dbh = C4::Context->dbh;
811     return $dbh->selectall_arrayref(q|
812         SELECT id, report, date_run
813         FROM saved_reports
814         WHERE report_id = ?
815     |, { Slice => {} }, $report_id);
816 }
817
818 sub _get_column_defs {
819     my ($cgi) = @_;
820     my %columns;
821     my $columns_def_file = "columns.def";
822     my $htdocs = C4::Context->config('intrahtdocs');
823     my $section = 'intranet';
824
825     # We need the theme and the lang
826     # Since columns.def is not in the modules directory, we cannot sent it for the $tmpl var
827     my ($theme, $lang, $availablethemes) = C4::Templates::themelanguage($htdocs, 'about.tt', $section, $cgi);
828
829     my $full_path_to_columns_def_file="$htdocs/$theme/$lang/$columns_def_file";
830     open (my $fh, '<:encoding(utf-8)', $full_path_to_columns_def_file);
831     while ( my $input = <$fh> ){
832         chomp $input;
833         if ( $input =~ m|<field name="(.*)">(.*)</field>| ) {
834             my ( $field, $translation ) = ( $1, $2 );
835             $columns{$field} = $translation;
836         }
837     }
838     close $fh;
839     return \%columns;
840 }
841
842 =head2 GetReservedAuthorisedValues
843
844     my %reserved_authorised_values = GetReservedAuthorisedValues();
845
846 Returns a hash containig all reserved words
847
848 =cut
849
850 sub GetReservedAuthorisedValues {
851     my %reserved_authorised_values =
852             map { $_ => 1 } ( 'date',
853                               'branches',
854                               'itemtypes',
855                               'cn_source',
856                               'categorycode',
857                               'biblio_framework' );
858
859    return \%reserved_authorised_values;
860 }
861
862
863 =head2 IsAuthorisedValueValid
864
865     my $is_valid_ath_value = IsAuthorisedValueValid($authorised_value)
866
867 Returns 1 if $authorised_value is on the reserved authorised values list or
868 in the authorised value categories defined in
869
870 =cut
871
872 sub IsAuthorisedValueValid {
873
874     my $authorised_value = shift;
875     my $reserved_authorised_values = GetReservedAuthorisedValues();
876
877     if ( exists $reserved_authorised_values->{$authorised_value} ||
878          Koha::AuthorisedValues->search({ category => $authorised_value })->count ) {
879         return 1;
880     }
881
882     return 0;
883 }
884
885 =head2 GetParametersFromSQL
886
887     my @sql_parameters = GetParametersFromSQL($sql)
888
889 Returns an arrayref of hashes containing the keys name and authval
890
891 =cut
892
893 sub GetParametersFromSQL {
894
895     my $sql = shift ;
896     my @split = split(/<<|>>/,$sql);
897     my @sql_parameters = ();
898
899     for ( my $i = 0; $i < ($#split/2) ; $i++ ) {
900         my ($name,$authval) = split(/\|/,$split[$i*2+1]);
901         push @sql_parameters, { 'name' => $name, 'authval' => $authval };
902     }
903
904     return \@sql_parameters;
905 }
906
907 =head2 ValidateSQLParameters
908
909     my @problematic_parameters = ValidateSQLParameters($sql)
910
911 Returns an arrayref of hashes containing the keys name and authval of
912 those SQL parameters that do not correspond to valid authorised names
913
914 =cut
915
916 sub ValidateSQLParameters {
917
918     my $sql = shift;
919     my @problematic_parameters = ();
920     my $sql_parameters = GetParametersFromSQL($sql);
921
922     foreach my $sql_parameter (@$sql_parameters) {
923         if ( defined $sql_parameter->{'authval'} ) {
924             push @problematic_parameters, $sql_parameter unless
925                 IsAuthorisedValueValid($sql_parameter->{'authval'});
926         }
927     }
928
929     return \@problematic_parameters;
930 }
931
932 sub _get_display_value {
933     my ( $original_value, $column ) = @_;
934     if ( $column eq 'periodicity' ) {
935         my $dbh = C4::Context->dbh();
936         my $query = "SELECT description FROM subscription_frequencies WHERE id = ?";
937         my $sth   = $dbh->prepare($query);
938         $sth->execute($original_value);
939         return $sth->fetchrow;
940     }
941     return $original_value;
942 }
943
944
945 =head3 convert_sql
946
947 my $updated_sql = C4::Reports::Guided::convert_sql( $sql );
948
949 Convert a sql query using biblioitems.marcxml to use the new
950 biblio_metadata.metadata field instead
951
952 =cut
953
954 sub convert_sql {
955     my ( $sql ) = @_;
956     my $updated_sql = $sql;
957     if ( $sql =~ m|biblioitems| and $sql =~ m|marcxml| ) {
958         $updated_sql =~ s|biblioitems|biblio_metadata|g;
959         $updated_sql =~ s|marcxml|metadata|g;
960     }
961     return $updated_sql;
962 }
963
964 1;
965 __END__
966
967 =head1 AUTHOR
968
969 Chris Cormack <crc@liblime.com>
970
971 =cut