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