Merge remote branch 'kc/master' into new/bug_5105
[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/;
28 use C4::Output;
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 = 0.12;
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         select_2_select_count_value 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
119 =head1 METHODS
120
121 =over 2
122
123 =cut
124
125 =item get_report_types()
126
127 This will return a list of all the available report types
128
129 =cut
130
131 sub get_report_types {
132     my $dbh = C4::Context->dbh();
133
134     # FIXME these should be in the database perhaps
135     my @reports = ( 'Tabular', 'Summary', 'Matrix' );
136     my @reports2;
137     for ( my $i = 0 ; $i < 3 ; $i++ ) {
138         my %hashrep;
139         $hashrep{id}   = $i + 1;
140         $hashrep{name} = $reports[$i];
141         push @reports2, \%hashrep;
142     }
143     return ( \@reports2 );
144
145 }
146
147 =item get_report_areas()
148
149 This will return a list of all the available report areas
150
151 =cut
152
153 sub get_report_areas {
154     my $dbh = C4::Context->dbh();
155
156     # FIXME these should be in the database
157     my @reports = ( 'Circulation', 'Catalog', 'Patrons', 'Acquisitions', 'Accounts');
158     my @reports2;
159     for ( my $i = 0 ; $i < 5 ; $i++ ) {
160         my %hashrep;
161         $hashrep{id}   = $i + 1;
162         $hashrep{name} = $reports[$i];
163         push @reports2, \%hashrep;
164     }
165     return ( \@reports2 );
166
167 }
168
169 =item get_all_tables()
170
171 This will return a list of all tables in the database 
172
173 =cut
174
175 sub get_all_tables {
176     my $dbh   = C4::Context->dbh();
177     my $query = "SHOW TABLES";
178     my $sth   = $dbh->prepare($query);
179     $sth->execute();
180     my @tables;
181     while ( my $data = $sth->fetchrow_arrayref() ) {
182         push @tables, $data->[0];
183     }
184     $sth->finish();
185     return ( \@tables );
186
187 }
188
189 =item get_columns($area)
190
191 This will return a list of all columns for a report area
192
193 =cut
194
195 sub get_columns {
196
197     # this calls the internal fucntion _get_columns
198     my ($area,$cgi) = @_;
199     my $tables = $table_areas{$area};
200     my @allcolumns;
201     my $first = 1;
202     foreach my $table (@$tables) {
203         my @columns = _get_columns($table,$cgi, $first);
204         $first = 0;
205         push @allcolumns, @columns;
206     }
207     return ( \@allcolumns );
208 }
209
210 sub _get_columns {
211     my ($tablename,$cgi, $first) = @_;
212     my $dbh         = C4::Context->dbh();
213     my $sth         = $dbh->prepare("show columns from $tablename");
214     $sth->execute();
215     my @columns;
216         my $column_defs = _get_column_defs($cgi);
217         my %tablehash;
218         $tablehash{'table'}=$tablename;
219     $tablehash{'__first__'} = $first;
220         push @columns, \%tablehash;
221     while ( my $data = $sth->fetchrow_arrayref() ) {
222         my %temphash;
223         $temphash{'name'}        = "$tablename.$data->[0]";
224         $temphash{'description'} = $column_defs->{"$tablename.$data->[0]"};
225         push @columns, \%temphash;
226     }
227     $sth->finish();
228     return (@columns);
229 }
230
231 =item build_query($columns,$criteria,$orderby,$area)
232
233 This will build the sql needed to return the results asked for, 
234 $columns is expected to be of the format tablename.columnname.
235 This is what get_columns returns.
236
237 =cut
238
239 sub build_query {
240     my ( $columns, $criteria, $orderby, $area, $totals, $definition ) = @_;
241 ### $orderby
242     my $keys   = $keys{$area};
243     my $tables = $table_areas{$area};
244
245     my $sql =
246       _build_query( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition );
247     return ($sql);
248 }
249
250 sub _build_query {
251     my ( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition) = @_;
252 ### $orderby
253     # $keys is an array of joining constraints
254     my $dbh           = C4::Context->dbh();
255     my $joinedtables  = join( ',', @$tables );
256     my $joinedcolumns = join( ',', @$columns );
257     my $query =
258       "SELECT $totals $joinedcolumns FROM $tables->[0] ";
259         for (my $i=1;$i<@$tables;$i++){
260                 $query .= "LEFT JOIN $tables->[$i] on ($keys->[$i-1]) ";
261         }
262
263     if ($criteria) {
264                 $criteria =~ s/AND/WHERE/;
265         $query .= " $criteria";
266     }
267         if ($definition){
268                 my @definitions = split(',',$definition);
269                 my $deftext;
270                 foreach my $def (@definitions){
271                         my $defin=get_from_dictionary('',$def);
272                         $deftext .=" ".$defin->[0]->{'saved_sql'};
273                 }
274                 if ($query =~ /WHERE/i){
275                         $query .= $deftext;
276                 }
277                 else {
278                         $deftext  =~ s/AND/WHERE/;
279                         $query .= $deftext;                     
280                 }
281         }
282     if ($totals) {
283         my $groupby;
284         my @totcolumns = split( ',', $totals );
285         foreach my $total (@totcolumns) {
286             if ( $total =~ /\((.*)\)/ ) {
287                 if ( $groupby eq '' ) {
288                     $groupby = " GROUP BY $1";
289                 }
290                 else {
291                     $groupby .= ",$1";
292                 }
293             }
294         }
295         $query .= $groupby;
296     }
297     if ($orderby) {
298         $query .= $orderby;
299     }
300     return ($query);
301 }
302
303 =item get_criteria($area,$cgi);
304
305 Returns an arraref to hashrefs suitable for using in a tmpl_loop. With the criteria and available values.
306
307 =cut
308
309 sub get_criteria {
310     my ($area,$cgi) = @_;
311     my $dbh    = C4::Context->dbh();
312     my $crit   = $criteria{$area};
313     my $column_defs = _get_column_defs($cgi);
314     my @criteria_array;
315     foreach my $localcrit (@$crit) {
316         my ( $value, $type )   = split( /\|/, $localcrit );
317         my ( $table, $column ) = split( /\./, $value );
318         if ($type eq 'textrange') {
319             my %temp;
320             $temp{'name'}        = $value;
321             $temp{'from'}        = "from_" . $value;
322             $temp{'to'}          = "to_" . $value;
323             $temp{'textrange'}   = 1;
324             $temp{'description'} = $column_defs->{$value};
325             push @criteria_array, \%temp;
326         }
327         elsif ($type eq 'date') {
328             my %temp;
329             $temp{'name'}        = $value;
330             $temp{'date'}        = 1;
331             $temp{'description'} = $column_defs->{$value};
332             push @criteria_array, \%temp;
333         }
334         elsif ($type eq 'daterange') {
335             my %temp;
336             $temp{'name'}        = $value;
337             $temp{'from'}        = "from_" . $value;
338             $temp{'to'}          = "to_" . $value;
339             $temp{'daterange'}   = 1;
340             $temp{'description'} = $column_defs->{$value};
341             push @criteria_array, \%temp;
342         }
343         else {
344             my $query =
345             "SELECT distinct($column) as availablevalues FROM $table";
346             my $sth = $dbh->prepare($query);
347             $sth->execute();
348             my @values;
349             # push the runtime choosing option
350             my $list;
351             $list='branches' if $column eq 'branchcode' or $column eq 'holdingbranch' or $column eq 'homebranch';
352             $list='categorycode' if $column eq 'categorycode';
353             $list='itemtype' if $column eq 'itype';
354             $list='ccode' if $column eq 'ccode';
355             # TODO : improve to let the librarian choose the description at runtime
356             push @values, { availablevalues => "<<$column".($list?"|$list":'').">>" };
357             while ( my $row = $sth->fetchrow_hashref() ) {
358                 push @values, $row;
359                 if ($row->{'availablevalues'} eq '') { $row->{'default'} = 1 };
360             }
361             $sth->finish();
362
363             my %temp;
364             $temp{'name'}        = $value;
365             $temp{'description'} = $column_defs->{$value};
366             $temp{'values'}      = \@values;
367
368             push @criteria_array, \%temp;
369         }
370
371     }
372     return ( \@criteria_array );
373 }
374
375 =item execute_query
376
377 =over
378
379 ($results, $total, $error) = execute_query($sql, $offset, $limit)
380
381 =back
382
383     When passed C<$sql>, this function returns an array ref containing a result set
384     suitably formatted for display in html or for output as a flat file when passed in
385     C<$format> and C<$id>. It also returns the C<$total> records available for the
386     supplied query. If passed any query other than a SELECT, or if there is a db error,
387     C<$errors> an array ref is returned containing the error after this manner:
388
389     C<$error->{'sqlerr'}> contains the offending SQL keyword.
390     C<$error->{'queryerr'}> contains the native db engine error returned for the query.
391     
392     Valid values for C<$format> are 'text,' 'tab,' 'csv,' or 'url. C<$sql>, C<$type>,
393     C<$offset>, and C<$limit> are required parameters. If a valid C<$format> is passed
394     in, C<$offset> and C<$limit> are ignored for obvious reasons. A LIMIT specified by
395     the user in a user-supplied SQL query WILL apply in any case.
396
397 =cut
398
399 # returns $sql, $offset, $limit
400 # $sql returned will be transformed to:
401 #  ~ remove any LIMIT clause
402 #  ~ repace SELECT clause w/ SELECT count(*)
403
404 sub select_2_select_count_value ($) {
405     my $sql = shift or return;
406     my $countsql = select_2_select_count($sql);
407     $debug and warn "original query: $sql\ncount query: $countsql\n";
408     my $sth1 = C4::Context->dbh->prepare($countsql);
409     $sth1->execute();
410     my $total = $sth1->fetchrow();
411     $debug and warn "total records for this query: $total\n";
412     return $total;
413 }
414 sub select_2_select_count ($) {
415     # Modify the query passed in to create a count query... (I think this covers all cases -crn)
416     my ($sql) = strip_limit(shift) or return;
417     $sql =~ s/\bSELECT\W+(?:\w+\W+){1,}?FROM\b|\bSELECT\W\*\WFROM\b/SELECT count(*) FROM /ig;
418     return $sql;
419 }
420 sub strip_limit ($) {
421     my $sql = shift or return;
422     ($sql =~ /\bLIMIT\b/i) or return ($sql, 0, undef);
423     $sql =~ s/\bLIMIT\b\s*(\d+)(\s*\,\s*(\d+))?\s*/ /ig;
424     return ($sql, (defined $2 ? $1 : 0), (defined $3 ? $3 : $1));   # offset can default to 0, LIMIT cannot!
425 }
426
427 sub execute_query ($;$$$) {
428
429     my ( $sql, $offset, $limit, $no_count ) = @_;
430
431     # check parameters
432     unless ($sql) {
433         carp "execute_query() called without SQL argument";
434         return;
435     }
436     $offset = 0    unless $offset;
437     $limit  = 9999 unless $limit;
438     $debug and print STDERR "execute_query($sql, $offset, $limit)\n";
439     if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
440         return (undef, {  sqlerr => $1} );
441     } elsif ($sql !~ /^\s*SELECT\b\s*/i) {
442         return (undef, { queryerr => 'Missing SELECT'} );
443     }
444
445     my ($useroffset, $userlimit);
446
447     # Grab offset/limit from user supplied LIMIT and drop the LIMIT so we can control pagination
448     ($sql, $useroffset, $userlimit) = strip_limit($sql);
449     $debug and warn sprintf "User has supplied (OFFSET,) LIMIT = %s, %s",
450         $useroffset,
451         (defined($userlimit ) ? $userlimit  : 'UNDEF');
452     $offset += $useroffset;
453     if (defined($userlimit)) {
454         if ($offset + $limit > $userlimit ) {
455             $limit = $userlimit - $offset;
456         } elsif ( ! $offset && $limit < $userlimit ) {
457             $limit = $userlimit;
458         }
459     }
460     $sql .= " LIMIT ?, ?";
461
462     my $sth = C4::Context->dbh->prepare($sql);
463     $sth->execute($offset, $limit);
464     return ( $sth );
465     # my @xmlarray = ... ;
466     # my $url = "/cgi-bin/koha/reports/guided_reports.pl?phase=retrieve%20results&id=$id";
467     # my $xml = XML::Dumper->new()->pl2xml( \@xmlarray );
468     # store_results($id,$xml);
469 }
470
471 =item save_report($sql,$name,$type,$notes)
472
473 Given some sql and a name this will saved it so that it can resued
474
475 =cut
476
477 sub save_report {
478     my ( $borrowernumber, $sql, $name, $type, $notes ) = @_;
479     my $dbh = C4::Context->dbh();
480     $sql =~ s/(\s*\;\s*)$//; # removes trailing whitespace and /;/
481     my $query =
482 "INSERT INTO saved_sql (borrowernumber,date_created,last_modified,savedsql,report_name,type,notes)  VALUES (?,now(),now(),?,?,?,?)";
483     my $sth = $dbh->prepare($query);
484     $sth->execute( $borrowernumber, $sql, $name, $type, $notes );
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 $dbh = C4::Context->dbh();
493     $sql =~ s/(\s*\;\s*)$//; # removes trailing whitespace and /;/
494     my $query = "UPDATE saved_sql SET savedsql = ?, last_modified = now(), report_name = ?, notes = ? WHERE id = ? ";
495     my $sth = $dbh->prepare($query);
496     $sth->execute( $sql, $reportname, $notes, $id );
497     $sth->finish();
498 }
499
500 sub store_results {
501         my ($id,$xml)=@_;
502         my $dbh = C4::Context->dbh();
503         my $query = "SELECT * FROM saved_reports WHERE report_id=?";
504         my $sth = $dbh->prepare($query);
505         $sth->execute($id);
506         if (my $data=$sth->fetchrow_hashref()){
507                 my $query2 = "UPDATE saved_reports SET report=?,date_run=now() WHERE report_id=?";
508                 my $sth2 = $dbh->prepare($query2);
509             $sth2->execute($xml,$id);
510         }
511         else {
512                 my $query2 = "INSERT INTO saved_reports (report_id,report,date_run) VALUES (?,?,now())";
513                 my $sth2 = $dbh->prepare($query2);
514                 $sth2->execute($id,$xml);
515         }
516 }
517
518 sub format_results {
519         my ($id) = @_;
520         my $dbh = C4::Context->dbh();
521         my $query = "SELECT * FROM saved_reports WHERE report_id = ?";
522         my $sth = $dbh->prepare($query);
523         $sth->execute($id);
524         my $data = $sth->fetchrow_hashref();
525         my $dump = new XML::Dumper;
526         my $perl = $dump->xml2pl( $data->{'report'} );
527         foreach my $row (@$perl) {
528                 my $htmlrow="<tr>";
529                 foreach my $key (keys %$row){
530                         $htmlrow .= "<td>$row->{$key}</td>";
531                 }
532                 $htmlrow .= "</tr>";
533                 $row->{'row'} = $htmlrow;
534         }
535         $sth->finish;
536         $query = "SELECT * FROM saved_sql WHERE id = ?";
537         $sth = $dbh->prepare($query);
538         $sth->execute($id);
539         $data = $sth->fetchrow_hashref();
540         return ($perl,$data->{'report_name'},$data->{'notes'}); 
541 }       
542
543 sub delete_report {
544         my ( $id ) = @_;
545         my $dbh = C4::Context->dbh();
546         my $query = "DELETE FROM saved_sql WHERE id = ?";
547         my $sth = $dbh->prepare($query);
548         $sth->execute($id);
549 }       
550
551 sub get_saved_reports {
552     my $dbh   = C4::Context->dbh();
553     my $query = "SELECT *,saved_sql.id AS id FROM saved_sql 
554     LEFT JOIN saved_reports ON saved_reports.report_id = saved_sql.id
555     ORDER by date_created";
556     my $sth   = $dbh->prepare($query);
557     $sth->execute();
558     
559     my $result = $sth->fetchall_arrayref({});
560     foreach (@$result){
561         $_->{date_created} = format_date($_->{date_created}); 
562         
563         my $member = C4::Members::GetMember(borrowernumber=>$_->{borrowernumber});
564         $_->{borrowerfirstname} = $member->{firstname};
565         $_->{borrowersurname}   = $member->{surname};
566     }
567     return $result;
568 }
569
570 sub get_saved_report {
571     my ($id)  = @_;
572     my $dbh   = C4::Context->dbh();
573     my $query = " SELECT * FROM saved_sql WHERE id = ?";
574     my $sth   = $dbh->prepare($query);
575     $sth->execute($id);
576     my $data = $sth->fetchrow_hashref();
577     return ( $data->{'savedsql'}, $data->{'type'}, $data->{'report_name'}, $data->{'notes'} );
578 }
579
580 =item create_compound($masterID,$subreportID)
581
582 This will take 2 reports and create a compound report using both of them
583
584 =cut
585
586 sub create_compound {
587         my ($masterID,$subreportID) = @_;
588         my $dbh = C4::Context->dbh();
589         # get the reports
590         my ($mastersql,$mastertype) = get_saved_report($masterID);
591         my ($subsql,$subtype) = get_saved_report($subreportID);
592         
593         # now we have to do some checking to see how these two will fit together
594         # or if they will
595         my ($mastertables,$subtables);
596         if ($mastersql =~ / from (.*) where /i){ 
597                 $mastertables = $1;
598         }
599         if ($subsql =~ / from (.*) where /i){
600                 $subtables = $1;
601         }
602         return ($mastertables,$subtables);
603 }
604
605 =item get_column_type($column)
606
607 This takes a column name of the format table.column and will return what type it is
608 (free text, set values, date)
609
610 =cut
611
612 sub get_column_type {
613         my ($tablecolumn) = @_;
614         my ($table,$column) = split(/\./,$tablecolumn);
615         my $dbh = C4::Context->dbh();
616         my $catalog;
617         my $schema;
618
619         # mysql doesnt support a column selection, set column to %
620         my $tempcolumn='%';
621         my $sth = $dbh->column_info( $catalog, $schema, $table, $tempcolumn ) || die $dbh->errstr;
622         while (my $info = $sth->fetchrow_hashref()){
623                 if ($info->{'COLUMN_NAME'} eq $column){
624                         #column we want
625                         if ($info->{'TYPE_NAME'} eq 'CHAR' || $info->{'TYPE_NAME'} eq 'VARCHAR'){
626                                 $info->{'TYPE_NAME'} = 'distinct';
627                         }
628                         return $info->{'TYPE_NAME'};            
629                 }
630         }
631 }
632
633 =item get_distinct_values($column)
634
635 Given a column name, return an arrary ref of hashrefs suitable for use as a tmpl_loop 
636 with the distinct values of the column
637
638 =cut
639
640 sub get_distinct_values {
641         my ($tablecolumn) = @_;
642         my ($table,$column) = split(/\./,$tablecolumn);
643         my $dbh = C4::Context->dbh();
644         my $query =
645           "SELECT distinct($column) as availablevalues FROM $table";
646         my $sth = $dbh->prepare($query);
647         $sth->execute();
648     return $sth->fetchall_arrayref({});
649 }       
650
651 sub save_dictionary {
652         my ($name,$description,$sql,$area) = @_;
653         my $dbh = C4::Context->dbh();
654         my $query = "INSERT INTO reports_dictionary (name,description,saved_sql,area,date_created,date_modified)
655   VALUES (?,?,?,?,now(),now())";
656     my $sth = $dbh->prepare($query);
657     $sth->execute($name,$description,$sql,$area) || return 0;
658     return 1;
659 }
660
661 sub get_from_dictionary {
662         my ($area,$id) = @_;
663         my $dbh = C4::Context->dbh();
664         my $query = "SELECT * FROM reports_dictionary";
665         if ($area){
666                 $query.= " WHERE area = ?";
667         }
668         elsif ($id){
669                 $query.= " WHERE id = ?"
670         }
671         my $sth = $dbh->prepare($query);
672         if ($id){
673                 $sth->execute($id);
674         }
675         elsif ($area) {
676                 $sth->execute($area);
677         }
678         else {
679                 $sth->execute();
680         }
681         my @loop;
682         my @reports = ( 'Circulation', 'Catalog', 'Patrons', 'Acquisitions', 'Accounts');
683         while (my $data = $sth->fetchrow_hashref()){
684                 $data->{'areaname'}=$reports[$data->{'area'}-1];
685                 push @loop,$data;
686                 
687         }
688         return (\@loop);
689 }
690
691 sub delete_definition {
692         my ($id) = @_ or return;
693         my $dbh = C4::Context->dbh();
694         my $query = "DELETE FROM reports_dictionary WHERE id = ?";
695         my $sth = $dbh->prepare($query);
696         $sth->execute($id);
697 }
698
699 sub get_sql {
700         my ($id) = @_ or return;
701         my $dbh = C4::Context->dbh();
702         my $query = "SELECT * FROM saved_sql WHERE id = ?";
703         my $sth = $dbh->prepare($query);
704         $sth->execute($id);
705         my $data=$sth->fetchrow_hashref();
706         return $data->{'savedsql'};
707 }
708
709 sub _get_column_defs {
710         my ($cgi) = @_;
711         my %columns;
712         my $columns_def_file = "columns.def";
713         my $htdocs = C4::Context->config('intrahtdocs');                       
714         my $section='intranet';
715         my ($theme, $lang) = themelanguage($htdocs, $columns_def_file, $section,$cgi);
716
717         my $full_path_to_columns_def_file="$htdocs/$theme/$lang/$columns_def_file";    
718         open (COLUMNS,$full_path_to_columns_def_file);
719         while (my $input = <COLUMNS>){
720                 my @row =split(/\t/,$input);
721                 $columns{$row[0]}=$row[1];
722         }
723
724         close COLUMNS;
725         return \%columns;
726 }
727 1;
728 __END__
729
730 =back
731
732 =head1 AUTHOR
733
734 Chris Cormack <crc@liblime.com>
735
736 =cut