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