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