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