Revert "Bug 6679: Fix 6 perlcritic violations in C4/Reports/Guided.pm"
[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
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 use Modern::Perl;
21 use CGI qw ( -utf8 );
22 use Carp;
23
24 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
25 use C4::Context;
26 use C4::Dates qw/format_date format_date_in_iso/;
27 use C4::Templates qw/themelanguage/;
28 use C4::Koha;
29 use C4::Output;
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 = 3.07.00.049;
39     require Exporter;
40     @ISA    = qw(Exporter);
41     @EXPORT = qw(
42       get_report_types get_report_areas get_report_groups 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       nb_rows update_sql build_authorised_value_list
47       GetReservedAuthorisedValues
48       GetParametersFromSQL
49       IsAuthorisedValueValid
50       ValidateSQLParameters
51       nb_rows update_sql
52     );
53 }
54
55 =head1 NAME
56
57 C4::Reports::Guided - Module for generating guided reports 
58
59 =head1 SYNOPSIS
60
61   use C4::Reports::Guided;
62
63 =head1 DESCRIPTION
64
65 =cut
66
67 =head1 METHODS
68
69 =head2 get_report_areas
70
71 This will return a list of all the available report areas
72
73 =cut
74
75 sub get_area_name_sql_snippet {
76     my @REPORT_AREA = (
77         [CIRC => "Circulation"],
78         [CAT  => "Catalogue"],
79         [PAT  => "Patrons"],
80         [ACQ  => "Acquisition"],
81         [ACC  => "Accounts"],
82         [SER  => "Serials"],
83     );
84
85     return "CASE report_area " .
86     join (" ", map "WHEN '$_->[0]' THEN '$_->[1]'", @REPORT_AREA) .
87     " END AS areaname";
88 }
89
90 sub get_report_areas {
91
92     my $report_areas = [ 'CIRC', 'CAT', 'PAT', 'ACQ', 'ACC', 'SER' ];
93
94     return $report_areas;
95 }
96
97 sub get_table_areas {
98     return (
99     CIRC => [ 'borrowers', 'statistics', 'items', 'biblioitems' ],
100     CAT  => [ 'items', 'biblioitems', 'biblio' ],
101     PAT  => ['borrowers'],
102     ACQ  => [ 'aqorders', 'biblio', 'items' ],
103     ACC  => [ 'borrowers', 'accountlines' ],
104     SER  => [ 'serial', 'serialitems', 'subscription', 'subscriptionhistory', 'subscriptionroutinglist', 'biblioitems', 'biblio', 'aqbooksellers' ],
105     );
106 }
107
108 =head2 get_report_types
109
110 This will return a list of all the available report types
111
112 =cut
113
114 sub get_report_types {
115     my $dbh = C4::Context->dbh();
116
117     # FIXME these should be in the database perhaps
118     my @reports = ( 'Tabular', 'Summary', 'Matrix' );
119     my @reports2;
120     for ( my $i = 0 ; $i < 3 ; $i++ ) {
121         my %hashrep;
122         $hashrep{id}   = $i + 1;
123         $hashrep{name} = $reports[$i];
124         push @reports2, \%hashrep;
125     }
126     return ( \@reports2 );
127
128 }
129
130 =head2 get_report_groups
131
132 This will return a list of all the available report areas with groups
133
134 =cut
135
136 sub get_report_groups {
137     my $dbh = C4::Context->dbh();
138
139     my $groups = GetAuthorisedValues('REPORT_GROUP');
140     my $subgroups = GetAuthorisedValues('REPORT_SUBGROUP');
141
142     my %groups_with_subgroups = map { $_->{authorised_value} => {
143                         name => $_->{lib},
144                         groups => {}
145                     } } @$groups;
146     foreach (@$subgroups) {
147         my $sg = $_->{authorised_value};
148         my $g = $_->{lib_opac}
149           or warn( qq{REPORT_SUBGROUP "$sg" without REPORT_GROUP (lib_opac)} ),
150              next;
151         my $g_sg = $groups_with_subgroups{$g}
152           or warn( qq{REPORT_SUBGROUP "$sg" with invalid REPORT_GROUP "$g"} ),
153              next;
154         $g_sg->{subgroups}{$sg} = $_->{lib};
155     }
156     return \%groups_with_subgroups
157 }
158
159 =head2 get_all_tables
160
161 This will return a list of all tables in the database 
162
163 =cut
164
165 sub get_all_tables {
166     my $dbh   = C4::Context->dbh();
167     my $query = "SHOW TABLES";
168     my $sth   = $dbh->prepare($query);
169     $sth->execute();
170     my @tables;
171     while ( my $data = $sth->fetchrow_arrayref() ) {
172         push @tables, $data->[0];
173     }
174     $sth->finish();
175     return ( \@tables );
176
177 }
178
179 =head2 get_columns($area)
180
181 This will return a list of all columns for a report area
182
183 =cut
184
185 sub get_columns {
186
187     # this calls the internal fucntion _get_columns
188     my ( $area, $cgi ) = @_;
189     my %table_areas = get_table_areas;
190     my $tables = $table_areas{$area}
191       or die qq{Unsuported report area "$area"};
192
193     my @allcolumns;
194     my $first = 1;
195     foreach my $table (@$tables) {
196         my @columns = _get_columns($table,$cgi, $first);
197         $first = 0;
198         push @allcolumns, @columns;
199     }
200     return ( \@allcolumns );
201 }
202
203 sub _get_columns {
204     my ($tablename,$cgi, $first) = @_;
205     my $dbh         = C4::Context->dbh();
206     my $sth         = $dbh->prepare("show columns from $tablename");
207     $sth->execute();
208     my @columns;
209         my $column_defs = _get_column_defs($cgi);
210         my %tablehash;
211         $tablehash{'table'}=$tablename;
212     $tablehash{'__first__'} = $first;
213         push @columns, \%tablehash;
214     while ( my $data = $sth->fetchrow_arrayref() ) {
215         my %temphash;
216         $temphash{'name'}        = "$tablename.$data->[0]";
217         $temphash{'description'} = $column_defs->{"$tablename.$data->[0]"};
218         push @columns, \%temphash;
219     }
220     $sth->finish();
221     return (@columns);
222 }
223
224 =head2 build_query($columns,$criteria,$orderby,$area)
225
226 This will build the sql needed to return the results asked for, 
227 $columns is expected to be of the format tablename.columnname.
228 This is what get_columns returns.
229
230 =cut
231
232 sub build_query {
233     my ( $columns, $criteria, $orderby, $area, $totals, $definition ) = @_;
234
235     my %keys = (
236         CIRC => [ 'statistics.borrowernumber=borrowers.borrowernumber',
237                   'items.itemnumber = statistics.itemnumber',
238                   'biblioitems.biblioitemnumber = items.biblioitemnumber' ],
239         CAT  => [ 'items.biblioitemnumber=biblioitems.biblioitemnumber',
240                   'biblioitems.biblionumber=biblio.biblionumber' ],
241         PAT  => [],
242         ACQ  => [ 'aqorders.biblionumber=biblio.biblionumber',
243                   'biblio.biblionumber=items.biblionumber' ],
244         ACC  => ['borrowers.borrowernumber=accountlines.borrowernumber'],
245         SER  => [ 'serial.serialid=serialitems.serialid', 'serial.subscriptionid=subscription.subscriptionid', 'serial.subscriptionid=subscriptionhistory.subscriptionid', 'serial.subscriptionid=subscriptionroutinglist.subscriptionid', 'biblioitems.biblionumber=serial.biblionumber', 'biblio.biblionumber=biblioitems.biblionumber', 'subscription.aqbooksellerid=aqbooksellers.id'],
246     );
247
248
249 ### $orderby
250     my $keys   = $keys{$area};
251     my %table_areas = get_table_areas;
252     my $tables = $table_areas{$area};
253
254     my $sql =
255       _build_query( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition );
256     return ($sql);
257 }
258
259 sub _build_query {
260     my ( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition) = @_;
261 ### $orderby
262     # $keys is an array of joining constraints
263     my $dbh           = C4::Context->dbh();
264     my $joinedtables  = join( ',', @$tables );
265     my $joinedcolumns = join( ',', @$columns );
266     my $query =
267       "SELECT $totals $joinedcolumns FROM $tables->[0] ";
268         for (my $i=1;$i<@$tables;$i++){
269                 $query .= "LEFT JOIN $tables->[$i] on ($keys->[$i-1]) ";
270         }
271
272     if ($criteria) {
273                 $criteria =~ s/AND/WHERE/;
274         $query .= " $criteria";
275     }
276         if ($definition){
277                 my @definitions = split(',',$definition);
278                 my $deftext;
279                 foreach my $def (@definitions){
280                         my $defin=get_from_dictionary('',$def);
281                         $deftext .=" ".$defin->[0]->{'saved_sql'};
282                 }
283                 if ($query =~ /WHERE/i){
284                         $query .= $deftext;
285                 }
286                 else {
287                         $deftext  =~ s/AND/WHERE/;
288                         $query .= $deftext;                     
289                 }
290         }
291     if ($totals) {
292         my $groupby;
293         my @totcolumns = split( ',', $totals );
294         foreach my $total (@totcolumns) {
295             if ( $total =~ /\((.*)\)/ ) {
296                 if ( $groupby eq '' ) {
297                     $groupby = " GROUP BY $1";
298                 }
299                 else {
300                     $groupby .= ",$1";
301                 }
302             }
303         }
304         $query .= $groupby;
305     }
306     if ($orderby) {
307         $query .= $orderby;
308     }
309     return ($query);
310 }
311
312 =head2 get_criteria($area,$cgi);
313
314 Returns an arraref to hashrefs suitable for using in a tmpl_loop. With the criteria and available values.
315
316 =cut
317
318 sub get_criteria {
319     my ($area,$cgi) = @_;
320     my $dbh    = C4::Context->dbh();
321
322     # have to do someting here to know if its dropdown, free text, date etc
323     my %criteria = (
324         CIRC => [ 'statistics.type', 'borrowers.categorycode', 'statistics.branch',
325                   'biblioitems.publicationyear|date', 'items.dateaccessioned|date' ],
326         CAT  => [ 'items.itemnumber|textrange', 'items.biblionumber|textrange',
327                   'items.barcode|textrange', 'biblio.frameworkcode',
328                   'items.holdingbranch', 'items.homebranch',
329                   'biblio.datecreated|daterange', 'biblio.timestamp|daterange',
330                   'items.onloan|daterange', 'items.ccode',
331                   'items.itemcallnumber|textrange', 'items.itype', 'items.itemlost',
332                   'items.location' ],
333         PAT  => [ 'borrowers.branchcode', 'borrowers.categorycode' ],
334         ACQ  => ['aqorders.datereceived|date'],
335         ACC  => [ 'borrowers.branchcode', 'borrowers.categorycode' ],
336         SER  => ['subscription.startdate|date', 'subscription.enddate|date', 'subscription.periodicity', 'subscription.callnumber', 'subscription.location', 'subscription.branchcode'],
337     );
338
339     # Adds itemtypes to criteria, according to the syspref
340     if ( C4::Context->preference('item-level_itypes') ) {
341         unshift @{ $criteria{'CIRC'} }, 'items.itype';
342         unshift @{ $criteria{'CAT'} }, 'items.itype';
343     } else {
344         unshift @{ $criteria{'CIRC'} }, 'biblioitems.itemtype';
345         unshift @{ $criteria{'CAT'} }, 'biblioitems.itemtype';
346     }
347
348
349     my $crit   = $criteria{$area};
350     my $column_defs = _get_column_defs($cgi);
351     my @criteria_array;
352     foreach my $localcrit (@$crit) {
353         my ( $value, $type )   = split( /\|/, $localcrit );
354         my ( $table, $column ) = split( /\./, $value );
355         if ($type eq 'textrange') {
356             my %temp;
357             $temp{'name'}        = $value;
358             $temp{'from'}        = "from_" . $value;
359             $temp{'to'}          = "to_" . $value;
360             $temp{'textrange'}   = 1;
361             $temp{'description'} = $column_defs->{$value};
362             push @criteria_array, \%temp;
363         }
364         elsif ($type eq 'date') {
365             my %temp;
366             $temp{'name'}        = $value;
367             $temp{'date'}        = 1;
368             $temp{'description'} = $column_defs->{$value};
369             push @criteria_array, \%temp;
370         }
371         elsif ($type eq 'daterange') {
372             my %temp;
373             $temp{'name'}        = $value;
374             $temp{'from'}        = "from_" . $value;
375             $temp{'to'}          = "to_" . $value;
376             $temp{'daterange'}   = 1;
377             $temp{'description'} = $column_defs->{$value};
378             push @criteria_array, \%temp;
379         }
380         else {
381             my $query =
382             "SELECT distinct($column) as availablevalues FROM $table";
383             my $sth = $dbh->prepare($query);
384             $sth->execute();
385             my @values;
386             # push the runtime choosing option
387             my $list;
388             $list='branches' if $column eq 'branchcode' or $column eq 'holdingbranch' or $column eq 'homebranch';
389             $list='categorycode' if $column eq 'categorycode';
390             $list='itemtypes' if $column eq 'itype';
391             $list='ccode' if $column eq 'ccode';
392             # TODO : improve to let the librarian choose the description at runtime
393             push @values, {
394                 availablevalues => "<<$column" . ( $list ? "|$list" : '' ) . ">>",
395                 display_value   => "<<$column" . ( $list ? "|$list" : '' ) . ">>",
396             };
397             while ( my $row = $sth->fetchrow_hashref() ) {
398                 if ($row->{'availablevalues'} eq '') { $row->{'default'} = 1 }
399                 else { $row->{display_value} = _get_display_value( $row->{'availablevalues'}, $column ); }
400                 push @values, $row;
401             }
402             $sth->finish();
403
404             my %temp;
405             $temp{'name'}        = $value;
406             $temp{'description'} = $column_defs->{$value};
407             $temp{'values'}      = \@values;
408
409             push @criteria_array, \%temp;
410         }
411     }
412     return ( \@criteria_array );
413 }
414
415 sub nb_rows {
416     my $sql = shift or return;
417     my $sth = C4::Context->dbh->prepare($sql);
418     $sth->execute();
419     my $rows = $sth->fetchall_arrayref();
420     return scalar (@$rows);
421 }
422
423 =head2 execute_query
424
425   ($sth, $error) = execute_query($sql, $offset, $limit[, \@sql_params])
426
427
428 This function returns a DBI statement handler from which the caller can
429 fetch the results of the SQL passed via C<$sql>.
430
431 If passed any query other than a SELECT, or if there is a DB error,
432 C<$errors> is returned, and is a hashref containing the error after this
433 manner:
434
435 C<$error->{'sqlerr'}> contains the offending SQL keyword.
436 C<$error->{'queryerr'}> contains the native db engine error returned
437 for the query.
438
439 C<$offset>, and C<$limit> are required parameters.
440
441 C<\@sql_params> is an optional list of parameter values to paste in.
442 The caller is reponsible for making sure that C<$sql> has placeholders
443 and that the number placeholders matches the number of parameters.
444
445 =cut
446
447 # returns $sql, $offset, $limit
448 # $sql returned will be transformed to:
449 #  ~ remove any LIMIT clause
450 #  ~ repace SELECT clause w/ SELECT count(*)
451
452 sub select_2_select_count {
453     # Modify the query passed in to create a count query... (I think this covers all cases -crn)
454     my ($sql) = strip_limit(shift) or return;
455     $sql =~ s/\bSELECT\W+(?:\w+\W+){1,}?FROM\b|\bSELECT\W\*\WFROM\b/SELECT count(*) FROM /ig;
456     return $sql;
457 }
458
459 # This removes the LIMIT from the query so that a custom one can be specified.
460 # Usage:
461 #   ($new_sql, $offset, $limit) = strip_limit($sql);
462 #
463 # Where:
464 #   $sql is the query to modify
465 #   $new_sql is the resulting query
466 #   $offset is the offset value, if the LIMIT was the two-argument form,
467 #       0 if it wasn't otherwise given.
468 #   $limit is the limit value
469 #
470 # Notes:
471 #   * This makes an effort to not break subqueries that have their own
472 #     LIMIT specified. It does that by only removing a LIMIT if it comes after
473 #     a WHERE clause (which isn't perfect, but at least should make more cases
474 #     work - subqueries with a limit in the WHERE will still break.)
475 #   * If your query doesn't have a WHERE clause then all LIMITs will be
476 #     removed. This may break some subqueries, but is hopefully rare enough
477 #     to not be a big issue.
478 sub strip_limit {
479     my ($sql) = @_;
480
481     return unless $sql;
482     return ($sql, 0, undef) unless $sql =~ /\bLIMIT\b/i;
483
484     # Two options: if there's no WHERE clause in the SQL, we simply capture
485     # any LIMIT that's there. If there is a WHERE, we make sure that we only
486     # capture a LIMIT after the last one. This prevents stomping on subqueries.
487     if ($sql !~ /\bWHERE\b/i) {
488         (my $res = $sql) =~ s/\bLIMIT\b\s*(\d+)(\s*\,\s*(\d+))?\s*/ /ig;
489         return ($res, (defined $2 ? $1 : 0), (defined $3 ? $3 : $1));
490     } else {
491         my $res = $sql;
492         $res =~ m/.*\bWHERE\b/gsi;
493         $res =~ s/\G(.*)\bLIMIT\b\s*(\d+)(\s*\,\s*(\d+))?\s*/$1 /is;
494         return ($res, (defined $3 ? $2 : 0), (defined $4 ? $4 : $2));
495     }
496 }
497
498 sub execute_query {
499
500     my ( $sql, $offset, $limit, $sql_params ) = @_;
501
502     $sql_params = [] unless defined $sql_params;
503
504     # check parameters
505     unless ($sql) {
506         carp "execute_query() called without SQL argument";
507         return;
508     }
509     $offset = 0    unless $offset;
510     $limit  = 999999 unless $limit;
511     $debug and print STDERR "execute_query($sql, $offset, $limit)\n";
512     if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
513         return (undef, {  sqlerr => $1} );
514     } elsif ($sql !~ /^\s*SELECT\b\s*/i) {
515         return (undef, { queryerr => 'Missing SELECT'} );
516     }
517
518     my ($useroffset, $userlimit);
519
520     # Grab offset/limit from user supplied LIMIT and drop the LIMIT so we can control pagination
521     ($sql, $useroffset, $userlimit) = strip_limit($sql);
522     $debug and warn sprintf "User has supplied (OFFSET,) LIMIT = %s, %s",
523         $useroffset,
524         (defined($userlimit ) ? $userlimit  : 'UNDEF');
525     $offset += $useroffset;
526     if (defined($userlimit)) {
527         if ($offset + $limit > $userlimit ) {
528             $limit = $userlimit - $offset;
529         } elsif ( ! $offset && $limit < $userlimit ) {
530             $limit = $userlimit;
531         }
532     }
533     $sql .= " LIMIT ?, ?";
534
535     my $sth = C4::Context->dbh->prepare($sql);
536     $sth->execute(@$sql_params, $offset, $limit);
537     return ( $sth, { queryerr => $sth->errstr } ) if ($sth->err);
538     return ( $sth );
539     # my @xmlarray = ... ;
540     # my $url = "/cgi-bin/koha/reports/guided_reports.pl?phase=retrieve%20results&id=$id";
541     # my $xml = XML::Dumper->new()->pl2xml( \@xmlarray );
542     # store_results($id,$xml);
543 }
544
545 =head2 save_report($sql,$name,$type,$notes)
546
547 Given some sql and a name this will saved it so that it can reused
548 Returns id of the newly created report
549
550 =cut
551
552 sub save_report {
553     my ($fields) = @_;
554     my $borrowernumber = $fields->{borrowernumber};
555     my $sql = $fields->{sql};
556     my $name = $fields->{name};
557     my $type = $fields->{type};
558     my $notes = $fields->{notes};
559     my $area = $fields->{area};
560     my $group = $fields->{group};
561     my $subgroup = $fields->{subgroup};
562     my $cache_expiry = $fields->{cache_expiry} || 300;
563     my $public = $fields->{public};
564
565     my $dbh = C4::Context->dbh();
566     $sql =~ s/(\s*\;\s*)$//;    # removes trailing whitespace and /;/
567     my $query = "INSERT INTO saved_sql (borrowernumber,date_created,last_modified,savedsql,report_name,report_area,report_group,report_subgroup,type,notes,cache_expiry,public)  VALUES (?,now(),now(),?,?,?,?,?,?,?,?,?)";
568     $dbh->do($query, undef, $borrowernumber, $sql, $name, $area, $group, $subgroup, $type, $notes, $cache_expiry, $public);
569
570     my $id = $dbh->selectrow_array("SELECT max(id) FROM saved_sql WHERE borrowernumber=? AND report_name=?", undef,
571                                    $borrowernumber, $name);
572     return $id;
573 }
574
575 sub update_sql {
576     my $id         = shift || croak "No Id given";
577     my $fields     = shift;
578     my $sql = $fields->{sql};
579     my $name = $fields->{name};
580     my $notes = $fields->{notes};
581     my $group = $fields->{group};
582     my $subgroup = $fields->{subgroup};
583     my $cache_expiry = $fields->{cache_expiry};
584     my $public = $fields->{public};
585
586     if( $cache_expiry >= 2592000 ){
587       die "Please specify a cache expiry less than 30 days\n";
588     }
589
590     my $dbh        = C4::Context->dbh();
591     $sql =~ s/(\s*\;\s*)$//;    # removes trailing whitespace and /;/
592     my $query = "UPDATE saved_sql SET savedsql = ?, last_modified = now(), report_name = ?, report_group = ?, report_subgroup = ?, notes = ?, cache_expiry = ?, public = ? WHERE id = ? ";
593     $dbh->do($query, undef, $sql, $name, $group, $subgroup, $notes, $cache_expiry, $public, $id );
594 }
595
596 sub store_results {
597         my ($id,$xml)=@_;
598         my $dbh = C4::Context->dbh();
599         my $query = "SELECT * FROM saved_reports WHERE report_id=?";
600         my $sth = $dbh->prepare($query);
601         $sth->execute($id);
602         if (my $data=$sth->fetchrow_hashref()){
603                 my $query2 = "UPDATE saved_reports SET report=?,date_run=now() WHERE report_id=?";
604                 my $sth2 = $dbh->prepare($query2);
605             $sth2->execute($xml,$id);
606         }
607         else {
608                 my $query2 = "INSERT INTO saved_reports (report_id,report,date_run) VALUES (?,?,now())";
609                 my $sth2 = $dbh->prepare($query2);
610                 $sth2->execute($id,$xml);
611         }
612 }
613
614 sub format_results {
615         my ($id) = @_;
616         my $dbh = C4::Context->dbh();
617         my $query = "SELECT * FROM saved_reports WHERE report_id = ?";
618         my $sth = $dbh->prepare($query);
619         $sth->execute($id);
620         my $data = $sth->fetchrow_hashref();
621         my $dump = new XML::Dumper;
622         my $perl = $dump->xml2pl( $data->{'report'} );
623         foreach my $row (@$perl) {
624                 my $htmlrow="<tr>";
625                 foreach my $key (keys %$row){
626                         $htmlrow .= "<td>$row->{$key}</td>";
627                 }
628                 $htmlrow .= "</tr>";
629                 $row->{'row'} = $htmlrow;
630         }
631         $sth->finish;
632         $query = "SELECT * FROM saved_sql WHERE id = ?";
633         $sth = $dbh->prepare($query);
634         $sth->execute($id);
635         $data = $sth->fetchrow_hashref();
636         return ($perl,$data->{'report_name'},$data->{'notes'}); 
637 }       
638
639 sub delete_report {
640     my (@ids) = @_;
641     return unless @ids;
642     my $dbh = C4::Context->dbh;
643     my $query = 'DELETE FROM saved_sql WHERE id IN (' . join( ',', ('?') x @ids ) . ')';
644     my $sth = $dbh->prepare($query);
645     return $sth->execute(@ids);
646 }
647
648 sub get_saved_reports_base_query {
649
650     my $area_name_sql_snippet = get_area_name_sql_snippet;
651     return <<EOQ;
652 SELECT s.*, r.report, r.date_run, $area_name_sql_snippet, av_g.lib AS groupname, av_sg.lib AS subgroupname,
653 b.firstname AS borrowerfirstname, b.surname AS borrowersurname
654 FROM saved_sql s
655 LEFT JOIN saved_reports r ON r.report_id = s.id
656 LEFT OUTER JOIN authorised_values av_g ON (av_g.category = 'REPORT_GROUP' AND av_g.authorised_value = s.report_group)
657 LEFT OUTER JOIN authorised_values av_sg ON (av_sg.category = 'REPORT_SUBGROUP' AND av_sg.lib_opac = s.report_group AND av_sg.authorised_value = s.report_subgroup)
658 LEFT OUTER JOIN borrowers b USING (borrowernumber)
659 EOQ
660 }
661
662 sub get_saved_reports {
663 # $filter is either { date => $d, author => $a, keyword => $kw, }
664 # or $keyword. Optional.
665     my ($filter) = @_;
666     $filter = { keyword => $filter } if $filter && !ref( $filter );
667     my ($group, $subgroup) = @_;
668
669     my $dbh   = C4::Context->dbh();
670     my $query = get_saved_reports_base_query;
671     my (@cond,@args);
672     if ($filter) {
673         if (my $date = $filter->{date}) {
674             $date = format_date_in_iso($date);
675             push @cond, "DATE(date_run) = ? OR
676                          DATE(date_created) = ? OR
677                          DATE(last_modified) = ? OR
678                          DATE(last_run) = ?";
679             push @args, $date, $date, $date, $date;
680         }
681         if (my $author = $filter->{author}) {
682             $author = "%$author%";
683             push @cond, "surname LIKE ? OR
684                          firstname LIKE ?";
685             push @args, $author, $author;
686         }
687         if (my $keyword = $filter->{keyword}) {
688             push @cond, q|
689                        report LIKE ?
690                     OR report_name LIKE ?
691                     OR notes LIKE ?
692                     OR savedsql LIKE ?
693                     OR s.id = ?
694             |;
695             push @args, "%$keyword%", "%$keyword%", "%$keyword%", "%$keyword%", $keyword;
696         }
697         if ($filter->{group}) {
698             push @cond, "report_group = ?";
699             push @args, $filter->{group};
700         }
701         if ($filter->{subgroup}) {
702             push @cond, "report_subgroup = ?";
703             push @args, $filter->{subgroup};
704         }
705     }
706     $query .= " WHERE ".join( " AND ", map "($_)", @cond ) if @cond;
707     $query .= " ORDER by date_created";
708     
709     my $result = $dbh->selectall_arrayref($query, {Slice => {}}, @args);
710
711     return $result;
712 }
713
714 sub get_saved_report {
715     my $dbh   = C4::Context->dbh();
716     my $query;
717     my $report_arg;
718     if ($#_ == 0 && ref $_[0] ne 'HASH') {
719         ($report_arg) = @_;
720         $query = " SELECT * FROM saved_sql WHERE id = ?";
721     } elsif (ref $_[0] eq 'HASH') {
722         my ($selector) = @_;
723         if ($selector->{name}) {
724             $query = " SELECT * FROM saved_sql WHERE report_name = ?";
725             $report_arg = $selector->{name};
726         } elsif ($selector->{id} || $selector->{id} eq '0') {
727             $query = " SELECT * FROM saved_sql WHERE id = ?";
728             $report_arg = $selector->{id};
729         } else {
730             return;
731         }
732     } else {
733         return;
734     }
735     return $dbh->selectrow_hashref($query, undef, $report_arg);
736 }
737
738 =head2 create_compound($masterID,$subreportID)
739
740 This will take 2 reports and create a compound report using both of them
741
742 =cut
743
744 sub create_compound {
745     my ( $masterID, $subreportID ) = @_;
746     my $dbh = C4::Context->dbh();
747
748     # get the reports
749     my $master = get_saved_report($masterID);
750     my $mastersql = $master->{savedsql};
751     my $mastertype = $master->{type};
752     my $sub = get_saved_report($subreportID);
753     my $subsql = $master->{savedsql};
754     my $subtype = $master->{type};
755
756     # now we have to do some checking to see how these two will fit together
757     # or if they will
758     my ( $mastertables, $subtables );
759     if ( $mastersql =~ / from (.*) where /i ) {
760         $mastertables = $1;
761     }
762     if ( $subsql =~ / from (.*) where /i ) {
763         $subtables = $1;
764     }
765     return ( $mastertables, $subtables );
766 }
767
768 =head2 get_column_type($column)
769
770 This takes a column name of the format table.column and will return what type it is
771 (free text, set values, date)
772
773 =cut
774
775 sub get_column_type {
776         my ($tablecolumn) = @_;
777         my ($table,$column) = split(/\./,$tablecolumn);
778         my $dbh = C4::Context->dbh();
779         my $catalog;
780         my $schema;
781
782         # mysql doesnt support a column selection, set column to %
783         my $tempcolumn='%';
784         my $sth = $dbh->column_info( $catalog, $schema, $table, $tempcolumn ) || die $dbh->errstr;
785         while (my $info = $sth->fetchrow_hashref()){
786                 if ($info->{'COLUMN_NAME'} eq $column){
787                         #column we want
788                         if ($info->{'TYPE_NAME'} eq 'CHAR' || $info->{'TYPE_NAME'} eq 'VARCHAR'){
789                                 $info->{'TYPE_NAME'} = 'distinct';
790                         }
791                         return $info->{'TYPE_NAME'};            
792                 }
793         }
794 }
795
796 =head2 get_distinct_values($column)
797
798 Given a column name, return an arrary ref of hashrefs suitable for use as a tmpl_loop 
799 with the distinct values of the column
800
801 =cut
802
803 sub get_distinct_values {
804         my ($tablecolumn) = @_;
805         my ($table,$column) = split(/\./,$tablecolumn);
806         my $dbh = C4::Context->dbh();
807         my $query =
808           "SELECT distinct($column) as availablevalues FROM $table";
809         my $sth = $dbh->prepare($query);
810         $sth->execute();
811     return $sth->fetchall_arrayref({});
812 }       
813
814 sub save_dictionary {
815     my ( $name, $description, $sql, $area ) = @_;
816     my $dbh   = C4::Context->dbh();
817     my $query = "INSERT INTO reports_dictionary (name,description,saved_sql,report_area,date_created,date_modified)
818   VALUES (?,?,?,?,now(),now())";
819     my $sth = $dbh->prepare($query);
820     $sth->execute($name,$description,$sql,$area) || return 0;
821     return 1;
822 }
823
824 sub get_from_dictionary {
825     my ( $area, $id ) = @_;
826     my $dbh   = C4::Context->dbh();
827     my $area_name_sql_snippet = get_area_name_sql_snippet;
828     my $query = <<EOQ;
829 SELECT d.*, $area_name_sql_snippet
830 FROM reports_dictionary d
831 EOQ
832
833     if ($area) {
834         $query .= " WHERE report_area = ?";
835     } elsif ($id) {
836         $query .= " WHERE id = ?";
837     }
838     my $sth = $dbh->prepare($query);
839     if ($id) {
840         $sth->execute($id);
841     } elsif ($area) {
842         $sth->execute($area);
843     } else {
844         $sth->execute();
845     }
846     my @loop;
847     while ( my $data = $sth->fetchrow_hashref() ) {
848         push @loop, $data;
849     }
850     return ( \@loop );
851 }
852
853 sub delete_definition {
854         my ($id) = @_ or return;
855         my $dbh = C4::Context->dbh();
856         my $query = "DELETE FROM reports_dictionary WHERE id = ?";
857         my $sth = $dbh->prepare($query);
858         $sth->execute($id);
859 }
860
861 sub get_sql {
862         my ($id) = @_ or return;
863         my $dbh = C4::Context->dbh();
864         my $query = "SELECT * FROM saved_sql WHERE id = ?";
865         my $sth = $dbh->prepare($query);
866         $sth->execute($id);
867         my $data=$sth->fetchrow_hashref();
868         return $data->{'savedsql'};
869 }
870
871 sub _get_column_defs {
872     my ($cgi) = @_;
873     my %columns;
874     my $columns_def_file = "columns.def";
875     my $htdocs = C4::Context->config('intrahtdocs');
876     my $section = 'intranet';
877
878     # We need the theme and the lang
879     # Since columns.def is not in the modules directory, we cannot sent it for the $tmpl var
880     my ($theme, $lang, $availablethemes) = C4::Templates::themelanguage($htdocs, 'about.tt', $section, $cgi);
881
882     my $full_path_to_columns_def_file="$htdocs/$theme/$lang/$columns_def_file";
883     open (my $fh, $full_path_to_columns_def_file);
884     while ( my $input = <$fh> ){
885         chomp $input;
886         if ( $input =~ m|<field name="(.*)">(.*)</field>| ) {
887             my ( $field, $translation ) = ( $1, $2 );
888             $columns{$field} = $translation;
889         }
890     }
891     close $fh;
892     return \%columns;
893 }
894
895 =head2 build_authorised_value_list($authorised_value)
896
897 Returns an arrayref - hashref pair. The hashref consists of
898 various code => name lists depending on the $authorised_value.
899 The arrayref is the hashref keys, in appropriate order
900
901 =cut
902
903 sub build_authorised_value_list {
904     my ( $authorised_value ) = @_;
905
906     my $dbh = C4::Context->dbh;
907     my @authorised_values;
908     my %authorised_lib;
909
910     # builds list, depending on authorised value...
911     if ( $authorised_value eq "branches" ) {
912         my $branches = GetBranchesLoop();
913         foreach my $thisbranch (@$branches) {
914             push @authorised_values, $thisbranch->{value};
915             $authorised_lib{ $thisbranch->{value} } = $thisbranch->{branchname};
916         }
917     } elsif ( $authorised_value eq "itemtypes" ) {
918         my $sth = $dbh->prepare("SELECT itemtype,description FROM itemtypes ORDER BY description");
919         $sth->execute;
920         while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
921             push @authorised_values, $itemtype;
922             $authorised_lib{$itemtype} = $description;
923         }
924     } elsif ( $authorised_value eq "cn_source" ) {
925         my $class_sources  = GetClassSources();
926         my $default_source = C4::Context->preference("DefaultClassificationSource");
927         foreach my $class_source ( sort keys %$class_sources ) {
928             next
929               unless $class_sources->{$class_source}->{'used'}
930                   or ( $class_source eq $default_source );
931             push @authorised_values, $class_source;
932             $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
933         }
934     } elsif ( $authorised_value eq "categorycode" ) {
935         my $sth = $dbh->prepare("SELECT categorycode, description FROM categories ORDER BY description");
936         $sth->execute;
937         while ( my ( $categorycode, $description ) = $sth->fetchrow_array ) {
938             push @authorised_values, $categorycode;
939             $authorised_lib{$categorycode} = $description;
940         }
941
942         #---- "true" authorised value
943     } else {
944         my $authorised_values_sth = $dbh->prepare("SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib");
945
946         $authorised_values_sth->execute($authorised_value);
947
948         while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
949             push @authorised_values, $value;
950             $authorised_lib{$value} = $lib;
951
952             # For item location, we show the code and the libelle
953             $authorised_lib{$value} = $lib;
954         }
955     }
956
957     return (\@authorised_values, \%authorised_lib);
958 }
959
960 =head2 GetReservedAuthorisedValues
961
962     my %reserved_authorised_values = GetReservedAuthorisedValues();
963
964 Returns a hash containig all reserved words
965
966 =cut
967
968 sub GetReservedAuthorisedValues {
969     my %reserved_authorised_values =
970             map { $_ => 1 } ( 'date',
971                               'branches',
972                               'itemtypes',
973                               'cn_source',
974                               'categorycode',
975                               'biblio_framework' );
976
977    return \%reserved_authorised_values;
978 }
979
980
981 =head2 IsAuthorisedValueValid
982
983     my $is_valid_ath_value = IsAuthorisedValueValid($authorised_value)
984
985 Returns 1 if $authorised_value is on the reserved authorised values list or
986 in the authorised value categories defined in
987
988 =cut
989
990 sub IsAuthorisedValueValid {
991
992     my $authorised_value = shift;
993     my $reserved_authorised_values = GetReservedAuthorisedValues();
994
995     if ( exists $reserved_authorised_values->{$authorised_value} ||
996          C4::Koha::IsAuthorisedValueCategory($authorised_value)   ) {
997         return 1;
998     }
999
1000     return 0;
1001 }
1002
1003 =head2 GetParametersFromSQL
1004
1005     my @sql_parameters = GetParametersFromSQL($sql)
1006
1007 Returns an arrayref of hashes containing the keys name and authval
1008
1009 =cut
1010
1011 sub GetParametersFromSQL {
1012
1013     my $sql = shift ;
1014     my @split = split(/<<|>>/,$sql);
1015     my @sql_parameters = ();
1016
1017     for ( my $i = 0; $i < ($#split/2) ; $i++ ) {
1018         my ($name,$authval) = split(/\|/,$split[$i*2+1]);
1019         push @sql_parameters, { 'name' => $name, 'authval' => $authval };
1020     }
1021
1022     return \@sql_parameters;
1023 }
1024
1025 =head2 ValidateSQLParameters
1026
1027     my @problematic_parameters = ValidateSQLParameters($sql)
1028
1029 Returns an arrayref of hashes containing the keys name and authval of
1030 those SQL parameters that do not correspond to valid authorised names
1031
1032 =cut
1033
1034 sub ValidateSQLParameters {
1035
1036     my $sql = shift;
1037     my @problematic_parameters = ();
1038     my $sql_parameters = GetParametersFromSQL($sql);
1039
1040     foreach my $sql_parameter (@$sql_parameters) {
1041         if ( defined $sql_parameter->{'authval'} ) {
1042             push @problematic_parameters, $sql_parameter unless
1043                 IsAuthorisedValueValid($sql_parameter->{'authval'});
1044         }
1045     }
1046
1047     return \@problematic_parameters;
1048 }
1049
1050 sub _get_display_value {
1051     my ( $original_value, $column ) = @_;
1052     if ( $column eq 'periodicity' ) {
1053         my $dbh = C4::Context->dbh();
1054         my $query = "SELECT description FROM subscription_frequencies WHERE id = ?";
1055         my $sth   = $dbh->prepare($query);
1056         $sth->execute($original_value);
1057         return $sth->fetchrow;
1058     }
1059     return $original_value;
1060 }
1061
1062 1;
1063 __END__
1064
1065 =head1 AUTHOR
1066
1067 Chris Cormack <crc@liblime.com>
1068
1069 =cut