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