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