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