Merge remote-tracking branch 'origin/new/bug_6720'
[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::Dates;
30 use XML::Simple;
31 use XML::Dumper;
32 use C4::Debug;
33 # use Smart::Comments;
34 # use Data::Dumper;
35
36 BEGIN {
37         # set the version for version checking
38     $VERSION = 3.07.00.049;
39         require Exporter;
40         @ISA = qw(Exporter);
41         @EXPORT = qw(
42                 get_report_types get_report_areas get_columns build_query get_criteria
43             save_report get_saved_reports execute_query get_saved_report create_compound run_compound
44                 get_column_type get_distinct_values save_dictionary get_from_dictionary
45                 delete_definition delete_report format_results get_sql
46         nb_rows update_sql
47         );
48 }
49
50 our %table_areas;
51 $table_areas{'1'} =
52   [ 'borrowers', 'statistics','items', 'biblioitems' ];    # circulation
53 $table_areas{'2'} = [ 'items', 'biblioitems', 'biblio' ];   # catalogue
54 $table_areas{'3'} = [ 'borrowers' ];        # patrons
55 $table_areas{'4'} = ['aqorders', 'biblio', 'items'];        # acquisitions
56 $table_areas{'5'} = [ 'borrowers', 'accountlines' ];        # accounts
57 our %keys;
58 $keys{'1'} = [
59     'statistics.borrowernumber=borrowers.borrowernumber',
60     'items.itemnumber = statistics.itemnumber',
61     'biblioitems.biblioitemnumber = items.biblioitemnumber'
62 ];
63 $keys{'2'} = [
64     'items.biblioitemnumber=biblioitems.biblioitemnumber',
65     'biblioitems.biblionumber=biblio.biblionumber'
66 ];
67 $keys{'3'} = [ ];
68 $keys{'4'} = [
69         'aqorders.biblionumber=biblio.biblionumber',
70         'biblio.biblionumber=items.biblionumber'
71 ];
72 $keys{'5'} = ['borrowers.borrowernumber=accountlines.borrowernumber'];
73
74 # have to do someting here to know if its dropdown, free text, date etc
75
76 our %criteria;
77 # reports on circulation
78 $criteria{'1'} = [
79     'statistics.type',   'borrowers.categorycode',
80     'statistics.branch',
81     'biblioitems.publicationyear|date',
82     'items.dateaccessioned|date'
83 ];
84 # reports on catalogue
85 $criteria{'2'} =
86   [ 'items.itemnumber|textrange',   'items.biblionumber|textrange',   'items.barcode|textrange', 
87     'biblio.frameworkcode',         'items.holdingbranch',            'items.homebranch', 
88   'biblio.datecreated|daterange',   'biblio.timestamp|daterange',     'items.onloan|daterange', 
89   'items.ccode',                    'items.itemcallnumber|textrange', 'items.itype', 
90   'items.itemlost',                 'items.location' ];
91 # reports on borrowers
92 $criteria{'3'} = ['borrowers.branchcode', 'borrowers.categorycode'];
93 # reports on acquisition
94 $criteria{'4'} = ['aqorders.datereceived|date'];
95
96 # reports on accounting
97 $criteria{'5'} = ['borrowers.branchcode', 'borrowers.categorycode'];
98
99 # Adds itemtypes to criteria, according to the syspref
100 if (C4::Context->preference('item-level_itypes')) {
101     unshift @{ $criteria{'1'} }, 'items.itype';
102     unshift @{ $criteria{'2'} }, 'items.itype';
103 } else {
104     unshift @{ $criteria{'1'} }, 'biblioitems.itemtype';
105     unshift @{ $criteria{'2'} }, 'biblioitems.itemtype';
106 }
107
108 =head1 NAME
109
110 C4::Reports::Guided - Module for generating guided reports 
111
112 =head1 SYNOPSIS
113
114   use C4::Reports::Guided;
115
116 =head1 DESCRIPTION
117
118 =cut
119
120 =head1 METHODS
121
122 =over 2
123
124 =cut
125
126 =item get_report_types()
127
128 This will return a list of all the available report types
129
130 =cut
131
132 sub get_report_types {
133     my $dbh = C4::Context->dbh();
134
135     # FIXME these should be in the database perhaps
136     my @reports = ( 'Tabular', 'Summary', 'Matrix' );
137     my @reports2;
138     for ( my $i = 0 ; $i < 3 ; $i++ ) {
139         my %hashrep;
140         $hashrep{id}   = $i + 1;
141         $hashrep{name} = $reports[$i];
142         push @reports2, \%hashrep;
143     }
144     return ( \@reports2 );
145
146 }
147
148 =item get_report_areas()
149
150 This will return a list of all the available report areas
151
152 =cut
153
154 sub get_report_areas {
155     my $dbh = C4::Context->dbh();
156
157     # FIXME these should be in the database
158     my @reports = ( 'Circulation', 'Catalog', 'Patrons', 'Acquisitions', 'Accounts');
159     my @reports2;
160     for ( my $i = 0 ; $i < 5 ; $i++ ) {
161         my %hashrep;
162         $hashrep{id}   = $i + 1;
163         $hashrep{name} = $reports[$i];
164         push @reports2, \%hashrep;
165     }
166     return ( \@reports2 );
167
168 }
169
170 =item get_all_tables()
171
172 This will return a list of all tables in the database 
173
174 =cut
175
176 sub get_all_tables {
177     my $dbh   = C4::Context->dbh();
178     my $query = "SHOW TABLES";
179     my $sth   = $dbh->prepare($query);
180     $sth->execute();
181     my @tables;
182     while ( my $data = $sth->fetchrow_arrayref() ) {
183         push @tables, $data->[0];
184     }
185     $sth->finish();
186     return ( \@tables );
187
188 }
189
190 =item get_columns($area)
191
192 This will return a list of all columns for a report area
193
194 =cut
195
196 sub get_columns {
197
198     # this calls the internal fucntion _get_columns
199     my ($area,$cgi) = @_;
200     my $tables = $table_areas{$area};
201     my @allcolumns;
202     my $first = 1;
203     foreach my $table (@$tables) {
204         my @columns = _get_columns($table,$cgi, $first);
205         $first = 0;
206         push @allcolumns, @columns;
207     }
208     return ( \@allcolumns );
209 }
210
211 sub _get_columns {
212     my ($tablename,$cgi, $first) = @_;
213     my $dbh         = C4::Context->dbh();
214     my $sth         = $dbh->prepare("show columns from $tablename");
215     $sth->execute();
216     my @columns;
217         my $column_defs = _get_column_defs($cgi);
218         my %tablehash;
219         $tablehash{'table'}=$tablename;
220     $tablehash{'__first__'} = $first;
221         push @columns, \%tablehash;
222     while ( my $data = $sth->fetchrow_arrayref() ) {
223         my %temphash;
224         $temphash{'name'}        = "$tablename.$data->[0]";
225         $temphash{'description'} = $column_defs->{"$tablename.$data->[0]"};
226         push @columns, \%temphash;
227     }
228     $sth->finish();
229     return (@columns);
230 }
231
232 =item build_query($columns,$criteria,$orderby,$area)
233
234 This will build the sql needed to return the results asked for, 
235 $columns is expected to be of the format tablename.columnname.
236 This is what get_columns returns.
237
238 =cut
239
240 sub build_query {
241     my ( $columns, $criteria, $orderby, $area, $totals, $definition ) = @_;
242 ### $orderby
243     my $keys   = $keys{$area};
244     my $tables = $table_areas{$area};
245
246     my $sql =
247       _build_query( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition );
248     return ($sql);
249 }
250
251 sub _build_query {
252     my ( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition) = @_;
253 ### $orderby
254     # $keys is an array of joining constraints
255     my $dbh           = C4::Context->dbh();
256     my $joinedtables  = join( ',', @$tables );
257     my $joinedcolumns = join( ',', @$columns );
258     my $query =
259       "SELECT $totals $joinedcolumns FROM $tables->[0] ";
260         for (my $i=1;$i<@$tables;$i++){
261                 $query .= "LEFT JOIN $tables->[$i] on ($keys->[$i-1]) ";
262         }
263
264     if ($criteria) {
265                 $criteria =~ s/AND/WHERE/;
266         $query .= " $criteria";
267     }
268         if ($definition){
269                 my @definitions = split(',',$definition);
270                 my $deftext;
271                 foreach my $def (@definitions){
272                         my $defin=get_from_dictionary('',$def);
273                         $deftext .=" ".$defin->[0]->{'saved_sql'};
274                 }
275                 if ($query =~ /WHERE/i){
276                         $query .= $deftext;
277                 }
278                 else {
279                         $deftext  =~ s/AND/WHERE/;
280                         $query .= $deftext;                     
281                 }
282         }
283     if ($totals) {
284         my $groupby;
285         my @totcolumns = split( ',', $totals );
286         foreach my $total (@totcolumns) {
287             if ( $total =~ /\((.*)\)/ ) {
288                 if ( $groupby eq '' ) {
289                     $groupby = " GROUP BY $1";
290                 }
291                 else {
292                     $groupby .= ",$1";
293                 }
294             }
295         }
296         $query .= $groupby;
297     }
298     if ($orderby) {
299         $query .= $orderby;
300     }
301     return ($query);
302 }
303
304 =item get_criteria($area,$cgi);
305
306 Returns an arraref to hashrefs suitable for using in a tmpl_loop. With the criteria and available values.
307
308 =cut
309
310 sub get_criteria {
311     my ($area,$cgi) = @_;
312     my $dbh    = C4::Context->dbh();
313     my $crit   = $criteria{$area};
314     my $column_defs = _get_column_defs($cgi);
315     my @criteria_array;
316     foreach my $localcrit (@$crit) {
317         my ( $value, $type )   = split( /\|/, $localcrit );
318         my ( $table, $column ) = split( /\./, $value );
319         if ($type eq 'textrange') {
320             my %temp;
321             $temp{'name'}        = $value;
322             $temp{'from'}        = "from_" . $value;
323             $temp{'to'}          = "to_" . $value;
324             $temp{'textrange'}   = 1;
325             $temp{'description'} = $column_defs->{$value};
326             push @criteria_array, \%temp;
327         }
328         elsif ($type eq 'date') {
329             my %temp;
330             $temp{'name'}        = $value;
331             $temp{'date'}        = 1;
332             $temp{'description'} = $column_defs->{$value};
333             push @criteria_array, \%temp;
334         }
335         elsif ($type eq 'daterange') {
336             my %temp;
337             $temp{'name'}        = $value;
338             $temp{'from'}        = "from_" . $value;
339             $temp{'to'}          = "to_" . $value;
340             $temp{'daterange'}   = 1;
341             $temp{'description'} = $column_defs->{$value};
342             push @criteria_array, \%temp;
343         }
344         else {
345             my $query =
346             "SELECT distinct($column) as availablevalues FROM $table";
347             my $sth = $dbh->prepare($query);
348             $sth->execute();
349             my @values;
350             # push the runtime choosing option
351             my $list;
352             $list='branches' if $column eq 'branchcode' or $column eq 'holdingbranch' or $column eq 'homebranch';
353             $list='categorycode' if $column eq 'categorycode';
354             $list='itemtype' if $column eq 'itype';
355             $list='ccode' if $column eq 'ccode';
356             # TODO : improve to let the librarian choose the description at runtime
357             push @values, { availablevalues => "<<$column".($list?"|$list":'').">>" };
358             while ( my $row = $sth->fetchrow_hashref() ) {
359                 push @values, $row;
360                 if ($row->{'availablevalues'} eq '') { $row->{'default'} = 1 };
361             }
362             $sth->finish();
363
364             my %temp;
365             $temp{'name'}        = $value;
366             $temp{'description'} = $column_defs->{$value};
367             $temp{'values'}      = \@values;
368
369             push @criteria_array, \%temp;
370         }
371
372     }
373     return ( \@criteria_array );
374 }
375
376 sub nb_rows($) {
377     my $sql = shift or return;
378     my $sth = C4::Context->dbh->prepare($sql);
379     $sth->execute();
380     my $rows = $sth->fetchall_arrayref();
381     return scalar (@$rows);
382 }
383
384 =item execute_query
385
386   ($results, $total, $error) = execute_query($sql, $offset, $limit)
387
388
389 When passed C<$sql>, this function returns an array ref containing a result set
390 suitably formatted for display in html or for output as a flat file when passed in
391 C<$format> and C<$id>. It also returns the C<$total> records available for the
392 supplied query. If passed any query other than a SELECT, or if there is a db error,
393 C<$errors> an array ref is returned containing the error after this manner:
394
395 C<$error->{'sqlerr'}> contains the offending SQL keyword.
396 C<$error->{'queryerr'}> contains the native db engine error returned for the query.
397
398 Valid values for C<$format> are 'text,' 'tab,' 'csv,' or 'url. C<$sql>, C<$type>,
399 C<$offset>, and C<$limit> are required parameters. If a valid C<$format> is passed
400 in, C<$offset> and C<$limit> are ignored for obvious reasons. A LIMIT specified by
401 the user in a user-supplied SQL query WILL apply in any case.
402
403 =cut
404
405 # returns $sql, $offset, $limit
406 # $sql returned will be transformed to:
407 #  ~ remove any LIMIT clause
408 #  ~ repace SELECT clause w/ SELECT count(*)
409
410 sub select_2_select_count ($) {
411     # Modify the query passed in to create a count query... (I think this covers all cases -crn)
412     my ($sql) = strip_limit(shift) or return;
413     $sql =~ s/\bSELECT\W+(?:\w+\W+){1,}?FROM\b|\bSELECT\W\*\WFROM\b/SELECT count(*) FROM /ig;
414     return $sql;
415 }
416 sub strip_limit ($) {
417     my $sql = shift or return;
418     ($sql =~ /\bLIMIT\b/i) or return ($sql, 0, undef);
419     $sql =~ s/\bLIMIT\b\s*(\d+)(\s*\,\s*(\d+))?\s*/ /ig;
420     return ($sql, (defined $2 ? $1 : 0), (defined $3 ? $3 : $1));   # offset can default to 0, LIMIT cannot!
421 }
422
423 sub execute_query ($;$$$) {
424
425     my ( $sql, $offset, $limit, $no_count ) = @_;
426
427     # check parameters
428     unless ($sql) {
429         carp "execute_query() called without SQL argument";
430         return;
431     }
432     $offset = 0    unless $offset;
433     $limit  = 999999 unless $limit;
434     $debug and print STDERR "execute_query($sql, $offset, $limit)\n";
435     if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
436         return (undef, {  sqlerr => $1} );
437     } elsif ($sql !~ /^\s*SELECT\b\s*/i) {
438         return (undef, { queryerr => 'Missing SELECT'} );
439     }
440
441     my ($useroffset, $userlimit);
442
443     # Grab offset/limit from user supplied LIMIT and drop the LIMIT so we can control pagination
444     ($sql, $useroffset, $userlimit) = strip_limit($sql);
445     $debug and warn sprintf "User has supplied (OFFSET,) LIMIT = %s, %s",
446         $useroffset,
447         (defined($userlimit ) ? $userlimit  : 'UNDEF');
448     $offset += $useroffset;
449     if (defined($userlimit)) {
450         if ($offset + $limit > $userlimit ) {
451             $limit = $userlimit - $offset;
452         } elsif ( ! $offset && $limit < $userlimit ) {
453             $limit = $userlimit;
454         }
455     }
456     $sql .= " LIMIT ?, ?";
457
458     my $sth = C4::Context->dbh->prepare($sql);
459     $sth->execute($offset, $limit);
460     return ( $sth );
461     # my @xmlarray = ... ;
462     # my $url = "/cgi-bin/koha/reports/guided_reports.pl?phase=retrieve%20results&id=$id";
463     # my $xml = XML::Dumper->new()->pl2xml( \@xmlarray );
464     # store_results($id,$xml);
465 }
466
467 =item save_report($sql,$name,$type,$notes)
468
469 Given some sql and a name this will saved it so that it can reused
470 Returns id of the newly created report
471
472 =cut
473
474 sub save_report {
475     my ( $borrowernumber, $sql, $name, $type, $notes, $cache_expiry, $public ) = @_;
476     $cache_expiry ||= 300;
477     my $dbh = C4::Context->dbh();
478     $sql =~ s/(\s*\;\s*)$//; # removes trailing whitespace and /;/
479     my $query =
480 "INSERT INTO saved_sql (borrowernumber,date_created,last_modified,savedsql,report_name,type,notes,cache_expiry, public)  VALUES (?,now(),now(),?,?,?,?,?,?)";
481     $dbh->do( $query, undef, $borrowernumber, $sql, $name, $type, $notes, $cache_expiry, $public );
482     my $id = $dbh->selectrow_array("SELECT max(id) FROM saved_sql WHERE borrowernumber=? AND report_name=?", undef,
483                                    $borrowernumber, $name);
484     return $id;
485 }
486
487 sub update_sql {
488     my $id = shift || croak "No Id given";
489     my $sql = shift;
490     my $reportname = shift;
491     my $notes = shift;
492     my $cache_expiry = shift;
493     my $public = shift;
494
495     # not entirely a magic number, Cache::Memcached::Set assumed any expiry >= (60*60*24*30) is an absolute unix timestamp (rather than relative seconds)
496     if( $cache_expiry >= 2592000 ){
497       die "Please specify a cache expiry less than 30 days\n";
498     }
499
500     my $dbh = C4::Context->dbh();
501     $sql =~ s/(\s*\;\s*)$//; # removes trailing whitespace and /;/
502     my $query = "UPDATE saved_sql SET savedsql = ?, last_modified = now(), report_name = ?, notes = ?, cache_expiry = ?, public = ? WHERE id = ? ";
503     my $sth = $dbh->prepare($query);
504     $sth->execute( $sql, $reportname, $notes, $cache_expiry, $public, $id );
505     $sth->finish();
506 }
507
508 sub store_results {
509         my ($id,$xml)=@_;
510         my $dbh = C4::Context->dbh();
511         my $query = "SELECT * FROM saved_reports WHERE report_id=?";
512         my $sth = $dbh->prepare($query);
513         $sth->execute($id);
514         if (my $data=$sth->fetchrow_hashref()){
515                 my $query2 = "UPDATE saved_reports SET report=?,date_run=now() WHERE report_id=?";
516                 my $sth2 = $dbh->prepare($query2);
517             $sth2->execute($xml,$id);
518         }
519         else {
520                 my $query2 = "INSERT INTO saved_reports (report_id,report,date_run) VALUES (?,?,now())";
521                 my $sth2 = $dbh->prepare($query2);
522                 $sth2->execute($id,$xml);
523         }
524 }
525
526 sub format_results {
527         my ($id) = @_;
528         my $dbh = C4::Context->dbh();
529         my $query = "SELECT * FROM saved_reports WHERE report_id = ?";
530         my $sth = $dbh->prepare($query);
531         $sth->execute($id);
532         my $data = $sth->fetchrow_hashref();
533         my $dump = new XML::Dumper;
534         my $perl = $dump->xml2pl( $data->{'report'} );
535         foreach my $row (@$perl) {
536                 my $htmlrow="<tr>";
537                 foreach my $key (keys %$row){
538                         $htmlrow .= "<td>$row->{$key}</td>";
539                 }
540                 $htmlrow .= "</tr>";
541                 $row->{'row'} = $htmlrow;
542         }
543         $sth->finish;
544         $query = "SELECT * FROM saved_sql WHERE id = ?";
545         $sth = $dbh->prepare($query);
546         $sth->execute($id);
547         $data = $sth->fetchrow_hashref();
548         return ($perl,$data->{'report_name'},$data->{'notes'}); 
549 }       
550
551 sub delete_report {
552         my ( $id ) = @_;
553         my $dbh = C4::Context->dbh();
554         my $query = "DELETE FROM saved_sql WHERE id = ?";
555         my $sth = $dbh->prepare($query);
556         $sth->execute($id);
557 }       
558
559 # $filter is either { date => $d, author => $a, keyword => $kw }
560 # or $keyword. Optional.
561 my $DATE_FORMAT = "%d/%m/%Y";
562 sub get_saved_reports {
563     my ($filter) = @_;
564     $filter = { keyword => $filter } if $filter && !ref( $filter );
565
566     my $dbh   = C4::Context->dbh();
567     my (@cond,@args);
568     my $query = "SELECT saved_sql.id, report_id, report,
569                         date_run, date_created, last_modified, savedsql, last_run,
570                         report_name, type, notes,
571                         borrowernumber, surname as borrowersurname, firstname as borrowerfirstname,
572                         cache_expiry, public
573                  FROM saved_sql 
574                  LEFT JOIN saved_reports ON saved_reports.report_id = saved_sql.id
575                  LEFT OUTER JOIN borrowers USING (borrowernumber)";
576     if ($filter) {
577         if (my $date = $filter->{date}) {
578             $date = format_date_in_iso($date);
579             push @cond, "DATE(date_run) = ? OR
580                          DATE(date_created) = ? OR
581                          DATE(last_modified) = ? OR
582                          DATE(last_run) = ?";
583             push @args, $date, $date, $date, $date;
584         }
585         if (my $author = $filter->{author}) {
586             $author = "%$author%";
587             push @cond, "surname LIKE ? OR
588                          firstname LIKE ?";
589             push @args, $author, $author;
590         }
591         if (my $keyword = $filter->{keyword}) {
592             $keyword = "%$keyword%";
593             push @cond, "report LIKE ? OR
594                          report_name LIKE ? OR
595                          notes LIKE ? OR
596                          savedsql LIKE ?";
597             push @args, $keyword, $keyword, $keyword, $keyword;
598         }
599     }
600     $query .= " WHERE ".join( " AND ", map "($_)", @cond ) if @cond;
601     $query .= " ORDER by date_created";
602     
603     my $result = $dbh->selectall_arrayref($query, {Slice => {}}, @args);
604     $_->{date_created} = format_date($_->{date_created}) foreach @$result;
605
606     return $result;
607 }
608
609 sub get_saved_report {
610     my $dbh   = C4::Context->dbh();
611     my $query;
612     my $sth;
613     my $report_arg;
614     if ($#_ == 0 && ref $_[0] ne 'HASH') {
615         ($report_arg) = @_;
616         $query = " SELECT * FROM saved_sql WHERE id = ?";
617     } elsif (ref $_[0] eq 'HASH') {
618         my ($selector) = @_;
619         if ($selector->{name}) {
620             $query = " SELECT * FROM saved_sql WHERE report_name = ?";
621             $report_arg = $selector->{name};
622         } elsif ($selector->{id} || $selector->{id} eq '0') {
623             $query = " SELECT * FROM saved_sql WHERE id = ?";
624             $report_arg = $selector->{id};
625         } else {
626             return;
627         }
628     } else {
629         return;
630     }
631     $sth   = $dbh->prepare($query);
632     $sth->execute($report_arg);
633     my $data = $sth->fetchrow_hashref();
634     return ( $data->{'savedsql'}, $data->{'type'}, $data->{'report_name'}, $data->{'notes'}, $data->{'cache_expiry'}, $data->{'public'}, $data->{'id'} );
635 }
636
637 =item create_compound($masterID,$subreportID)
638
639 This will take 2 reports and create a compound report using both of them
640
641 =cut
642
643 sub create_compound {
644         my ($masterID,$subreportID) = @_;
645         my $dbh = C4::Context->dbh();
646         # get the reports
647         my ($mastersql,$mastertype) = get_saved_report($masterID);
648         my ($subsql,$subtype) = get_saved_report($subreportID);
649         
650         # now we have to do some checking to see how these two will fit together
651         # or if they will
652         my ($mastertables,$subtables);
653         if ($mastersql =~ / from (.*) where /i){ 
654                 $mastertables = $1;
655         }
656         if ($subsql =~ / from (.*) where /i){
657                 $subtables = $1;
658         }
659         return ($mastertables,$subtables);
660 }
661
662 =item get_column_type($column)
663
664 This takes a column name of the format table.column and will return what type it is
665 (free text, set values, date)
666
667 =cut
668
669 sub get_column_type {
670         my ($tablecolumn) = @_;
671         my ($table,$column) = split(/\./,$tablecolumn);
672         my $dbh = C4::Context->dbh();
673         my $catalog;
674         my $schema;
675
676         # mysql doesnt support a column selection, set column to %
677         my $tempcolumn='%';
678         my $sth = $dbh->column_info( $catalog, $schema, $table, $tempcolumn ) || die $dbh->errstr;
679         while (my $info = $sth->fetchrow_hashref()){
680                 if ($info->{'COLUMN_NAME'} eq $column){
681                         #column we want
682                         if ($info->{'TYPE_NAME'} eq 'CHAR' || $info->{'TYPE_NAME'} eq 'VARCHAR'){
683                                 $info->{'TYPE_NAME'} = 'distinct';
684                         }
685                         return $info->{'TYPE_NAME'};            
686                 }
687         }
688 }
689
690 =item get_distinct_values($column)
691
692 Given a column name, return an arrary ref of hashrefs suitable for use as a tmpl_loop 
693 with the distinct values of the column
694
695 =cut
696
697 sub get_distinct_values {
698         my ($tablecolumn) = @_;
699         my ($table,$column) = split(/\./,$tablecolumn);
700         my $dbh = C4::Context->dbh();
701         my $query =
702           "SELECT distinct($column) as availablevalues FROM $table";
703         my $sth = $dbh->prepare($query);
704         $sth->execute();
705     return $sth->fetchall_arrayref({});
706 }       
707
708 sub save_dictionary {
709         my ($name,$description,$sql,$area) = @_;
710         my $dbh = C4::Context->dbh();
711         my $query = "INSERT INTO reports_dictionary (name,description,saved_sql,area,date_created,date_modified)
712   VALUES (?,?,?,?,now(),now())";
713     my $sth = $dbh->prepare($query);
714     $sth->execute($name,$description,$sql,$area) || return 0;
715     return 1;
716 }
717
718 sub get_from_dictionary {
719         my ($area,$id) = @_;
720         my $dbh = C4::Context->dbh();
721         my $query = "SELECT * FROM reports_dictionary";
722         if ($area){
723                 $query.= " WHERE area = ?";
724         }
725         elsif ($id){
726                 $query.= " WHERE id = ?"
727         }
728         my $sth = $dbh->prepare($query);
729         if ($id){
730                 $sth->execute($id);
731         }
732         elsif ($area) {
733                 $sth->execute($area);
734         }
735         else {
736                 $sth->execute();
737         }
738         my @loop;
739         my @reports = ( 'Circulation', 'Catalog', 'Patrons', 'Acquisitions', 'Accounts');
740         while (my $data = $sth->fetchrow_hashref()){
741                 $data->{'areaname'}=$reports[$data->{'area'}-1];
742                 push @loop,$data;
743                 
744         }
745         return (\@loop);
746 }
747
748 sub delete_definition {
749         my ($id) = @_ or return;
750         my $dbh = C4::Context->dbh();
751         my $query = "DELETE FROM reports_dictionary WHERE id = ?";
752         my $sth = $dbh->prepare($query);
753         $sth->execute($id);
754 }
755
756 sub get_sql {
757         my ($id) = @_ or return;
758         my $dbh = C4::Context->dbh();
759         my $query = "SELECT * FROM saved_sql WHERE id = ?";
760         my $sth = $dbh->prepare($query);
761         $sth->execute($id);
762         my $data=$sth->fetchrow_hashref();
763         return $data->{'savedsql'};
764 }
765
766 sub _get_column_defs {
767         my ($cgi) = @_;
768         my %columns;
769         my $columns_def_file = "columns.def";
770         my $htdocs = C4::Context->config('intrahtdocs');                       
771         my $section='intranet';
772         my ($theme, $lang) = C4::Templates::themelanguage($htdocs, $columns_def_file, $section,$cgi);
773
774         my $full_path_to_columns_def_file="$htdocs/$theme/$lang/$columns_def_file";    
775         open (COLUMNS,$full_path_to_columns_def_file);
776         while (my $input = <COLUMNS>){
777                 chomp $input;
778                 my @row =split(/\t/,$input);
779                 $columns{$row[0]}= $row[1];
780         }
781
782         close COLUMNS;
783         return \%columns;
784 }
785 1;
786 __END__
787
788 =back
789
790 =head1 AUTHOR
791
792 Chris Cormack <crc@liblime.com>
793
794 =cut