Bug 11944: replace use of utf8 with Encode
[koha.git] / C4 / Reports / Guided.pm
blobbb283fa4588fff77e20dcd06a6b6a9173aed6b66
1 package C4::Reports::Guided;
3 # Copyright 2007 Liblime Ltd
5 # This file is part of Koha.
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.
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.
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.
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;
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;
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
55 =head1 NAME
57 C4::Reports::Guided - Module for generating guided reports
59 =head1 SYNOPSIS
61 use C4::Reports::Guided;
63 =head1 DESCRIPTION
65 =cut
67 =head1 METHODS
69 =head2 get_report_areas
71 This will return a list of all the available report areas
73 =cut
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"],
84 return "CASE report_area " .
85 join (" ", map "WHEN '$_->[0]' THEN '$_->[1]'", @REPORT_AREA) .
86 " END AS areaname";
89 sub get_report_areas {
91 my $report_areas = [ 'CIRC', 'CAT', 'PAT', 'ACQ', 'ACC' ];
93 return $report_areas;
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' ],
106 =head2 get_report_types
108 This will return a list of all the available report types
110 =cut
112 sub get_report_types {
113 my $dbh = C4::Context->dbh();
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;
124 return ( \@reports2 );
128 =head2 get_report_groups
130 This will return a list of all the available report areas with groups
132 =cut
134 sub get_report_groups {
135 my $dbh = C4::Context->dbh();
137 my $groups = GetAuthorisedValues('REPORT_GROUP');
138 my $subgroups = GetAuthorisedValues('REPORT_SUBGROUP');
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};
154 return \%groups_with_subgroups
157 =head2 get_all_tables
159 This will return a list of all tables in the database
161 =cut
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];
172 $sth->finish();
173 return ( \@tables );
177 =head2 get_columns($area)
179 This will return a list of all columns for a report area
181 =cut
183 sub get_columns {
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"};
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;
198 return ( \@allcolumns );
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;
218 $sth->finish();
219 return (@columns);
222 =head2 build_query($columns,$criteria,$orderby,$area)
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.
228 =cut
230 sub build_query {
231 my ( $columns, $criteria, $orderby, $area, $totals, $definition ) = @_;
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'],
246 ### $orderby
247 my $keys = $keys{$area};
248 my %table_areas = get_table_areas;
249 my $tables = $table_areas{$area};
251 my $sql =
252 _build_query( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition );
253 return ($sql);
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]) ";
269 if ($criteria) {
270 $criteria =~ s/AND/WHERE/;
271 $query .= " $criteria";
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'};
280 if ($query =~ /WHERE/i){
281 $query .= $deftext;
283 else {
284 $deftext =~ s/AND/WHERE/;
285 $query .= $deftext;
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";
296 else {
297 $groupby .= ",$1";
301 $query .= $groupby;
303 if ($orderby) {
304 $query .= $orderby;
306 return ($query);
309 =head2 get_criteria($area,$cgi);
311 Returns an arraref to hashrefs suitable for using in a tmpl_loop. With the criteria and available values.
313 =cut
315 sub get_criteria {
316 my ($area,$cgi) = @_;
317 my $dbh = C4::Context->dbh();
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' ],
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';
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;
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;
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;
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='itemtype' 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 };
394 $sth->finish();
396 my %temp;
397 $temp{'name'} = $value;
398 $temp{'description'} = $column_defs->{$value};
399 $temp{'values'} = \@values;
401 push @criteria_array, \%temp;
405 return ( \@criteria_array );
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);
416 =head2 execute_query
418 ($sth, $error) = execute_query($sql, $offset, $limit[, \@sql_params])
421 This function returns a DBI statement handler from which the caller can
422 fetch the results of the SQL passed via C<$sql>.
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:
428 C<$error->{'sqlerr'}> contains the offending SQL keyword.
429 C<$error->{'queryerr'}> contains the native db engine error returned
430 for the query.
432 C<$offset>, and C<$limit> are required parameters.
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.
438 =cut
440 # returns $sql, $offset, $limit
441 # $sql returned will be transformed to:
442 # ~ remove any LIMIT clause
443 # ~ repace SELECT clause w/ SELECT count(*)
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;
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);
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
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) = @_;
474 return unless $sql;
475 return ($sql, 0, undef) unless $sql =~ /\bLIMIT\b/i;
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));
491 sub execute_query {
493 my ( $sql, $offset, $limit, $sql_params ) = @_;
495 $sql_params = [] unless defined $sql_params;
497 # check parameters
498 unless ($sql) {
499 carp "execute_query() called without SQL argument";
500 return;
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'} );
511 my ($useroffset, $userlimit);
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;
526 $sql .= " LIMIT ?, ?";
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);
538 =head2 save_report($sql,$name,$type,$notes)
540 Given some sql and a name this will saved it so that it can reused
541 Returns id of the newly created report
543 =cut
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};
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);
563 my $id = $dbh->selectrow_array("SELECT max(id) FROM saved_sql WHERE borrowernumber=? AND report_name=?", undef,
564 $borrowernumber, $name);
565 return $id;
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};
579 if( $cache_expiry >= 2592000 ){
580 die "Please specify a cache expiry less than 30 days\n";
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 );
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);
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);
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>";
621 $htmlrow .= "</tr>";
622 $row->{'row'} = $htmlrow;
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'});
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);
641 sub get_saved_reports_base_query {
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)
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) = @_;
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;
674 if (my $author = $filter->{author}) {
675 $author = "%$author%";
676 push @cond, "surname LIKE ? OR
677 firstname LIKE ?";
678 push @args, $author, $author;
680 if (my $keyword = $filter->{keyword}) {
681 $keyword = "%$keyword%";
682 push @cond, "report LIKE ? OR
683 report_name LIKE ? OR
684 notes LIKE ? OR
685 savedsql LIKE ?";
686 push @args, $keyword, $keyword, $keyword, $keyword;
688 if ($filter->{group}) {
689 push @cond, "report_group = ?";
690 push @args, $filter->{group};
692 if ($filter->{subgroup}) {
693 push @cond, "report_subgroup = ?";
694 push @args, $filter->{subgroup};
697 $query .= " WHERE ".join( " AND ", map "($_)", @cond ) if @cond;
698 $query .= " ORDER by date_created";
700 my $result = $dbh->selectall_arrayref($query, {Slice => {}}, @args);
702 return $result;
705 sub get_saved_report {
706 my $dbh = C4::Context->dbh();
707 my $query;
708 my $report_arg;
709 if ($#_ == 0 && ref $_[0] ne 'HASH') {
710 ($report_arg) = @_;
711 $query = " SELECT * FROM saved_sql WHERE id = ?";
712 } elsif (ref $_[0] eq 'HASH') {
713 my ($selector) = @_;
714 if ($selector->{name}) {
715 $query = " SELECT * FROM saved_sql WHERE report_name = ?";
716 $report_arg = $selector->{name};
717 } elsif ($selector->{id} || $selector->{id} eq '0') {
718 $query = " SELECT * FROM saved_sql WHERE id = ?";
719 $report_arg = $selector->{id};
720 } else {
721 return;
723 } else {
724 return;
726 return $dbh->selectrow_hashref($query, undef, $report_arg);
729 =head2 create_compound($masterID,$subreportID)
731 This will take 2 reports and create a compound report using both of them
733 =cut
735 sub create_compound {
736 my ( $masterID, $subreportID ) = @_;
737 my $dbh = C4::Context->dbh();
739 # get the reports
740 my $master = get_saved_report($masterID);
741 my $mastersql = $master->{savedsql};
742 my $mastertype = $master->{type};
743 my $sub = get_saved_report($subreportID);
744 my $subsql = $master->{savedsql};
745 my $subtype = $master->{type};
747 # now we have to do some checking to see how these two will fit together
748 # or if they will
749 my ( $mastertables, $subtables );
750 if ( $mastersql =~ / from (.*) where /i ) {
751 $mastertables = $1;
753 if ( $subsql =~ / from (.*) where /i ) {
754 $subtables = $1;
756 return ( $mastertables, $subtables );
759 =head2 get_column_type($column)
761 This takes a column name of the format table.column and will return what type it is
762 (free text, set values, date)
764 =cut
766 sub get_column_type {
767 my ($tablecolumn) = @_;
768 my ($table,$column) = split(/\./,$tablecolumn);
769 my $dbh = C4::Context->dbh();
770 my $catalog;
771 my $schema;
773 # mysql doesnt support a column selection, set column to %
774 my $tempcolumn='%';
775 my $sth = $dbh->column_info( $catalog, $schema, $table, $tempcolumn ) || die $dbh->errstr;
776 while (my $info = $sth->fetchrow_hashref()){
777 if ($info->{'COLUMN_NAME'} eq $column){
778 #column we want
779 if ($info->{'TYPE_NAME'} eq 'CHAR' || $info->{'TYPE_NAME'} eq 'VARCHAR'){
780 $info->{'TYPE_NAME'} = 'distinct';
782 return $info->{'TYPE_NAME'};
787 =head2 get_distinct_values($column)
789 Given a column name, return an arrary ref of hashrefs suitable for use as a tmpl_loop
790 with the distinct values of the column
792 =cut
794 sub get_distinct_values {
795 my ($tablecolumn) = @_;
796 my ($table,$column) = split(/\./,$tablecolumn);
797 my $dbh = C4::Context->dbh();
798 my $query =
799 "SELECT distinct($column) as availablevalues FROM $table";
800 my $sth = $dbh->prepare($query);
801 $sth->execute();
802 return $sth->fetchall_arrayref({});
805 sub save_dictionary {
806 my ( $name, $description, $sql, $area ) = @_;
807 my $dbh = C4::Context->dbh();
808 my $query = "INSERT INTO reports_dictionary (name,description,saved_sql,report_area,date_created,date_modified)
809 VALUES (?,?,?,?,now(),now())";
810 my $sth = $dbh->prepare($query);
811 $sth->execute($name,$description,$sql,$area) || return 0;
812 return 1;
815 sub get_from_dictionary {
816 my ( $area, $id ) = @_;
817 my $dbh = C4::Context->dbh();
818 my $area_name_sql_snippet = get_area_name_sql_snippet;
819 my $query = <<EOQ;
820 SELECT d.*, $area_name_sql_snippet
821 FROM reports_dictionary d
824 if ($area) {
825 $query .= " WHERE report_area = ?";
826 } elsif ($id) {
827 $query .= " WHERE id = ?";
829 my $sth = $dbh->prepare($query);
830 if ($id) {
831 $sth->execute($id);
832 } elsif ($area) {
833 $sth->execute($area);
834 } else {
835 $sth->execute();
837 my @loop;
838 while ( my $data = $sth->fetchrow_hashref() ) {
839 push @loop, $data;
841 return ( \@loop );
844 sub delete_definition {
845 my ($id) = @_ or return;
846 my $dbh = C4::Context->dbh();
847 my $query = "DELETE FROM reports_dictionary WHERE id = ?";
848 my $sth = $dbh->prepare($query);
849 $sth->execute($id);
852 sub get_sql {
853 my ($id) = @_ or return;
854 my $dbh = C4::Context->dbh();
855 my $query = "SELECT * FROM saved_sql WHERE id = ?";
856 my $sth = $dbh->prepare($query);
857 $sth->execute($id);
858 my $data=$sth->fetchrow_hashref();
859 return $data->{'savedsql'};
862 sub _get_column_defs {
863 my ($cgi) = @_;
864 my %columns;
865 my $columns_def_file = "columns.def";
866 my $htdocs = C4::Context->config('intrahtdocs');
867 my $section = 'intranet';
869 # We need the theme and the lang
870 # Since columns.def is not in the modules directory, we cannot sent it for the $tmpl var
871 my ($theme, $lang, $availablethemes) = C4::Templates::themelanguage($htdocs, 'about.tt', $section, $cgi);
873 my $full_path_to_columns_def_file="$htdocs/$theme/$lang/$columns_def_file";
874 open (my $fh, $full_path_to_columns_def_file);
875 while ( my $input = <$fh> ){
876 chomp $input;
877 if ( $input =~ m|<field name="(.*)">(.*)</field>| ) {
878 my ( $field, $translation ) = ( $1, $2 );
879 $columns{$field} = $translation;
882 close $fh;
883 return \%columns;
886 =head2 build_authorised_value_list($authorised_value)
888 Returns an arrayref - hashref pair. The hashref consists of
889 various code => name lists depending on the $authorised_value.
890 The arrayref is the hashref keys, in appropriate order
892 =cut
894 sub build_authorised_value_list {
895 my ( $authorised_value ) = @_;
897 my $dbh = C4::Context->dbh;
898 my @authorised_values;
899 my %authorised_lib;
901 # builds list, depending on authorised value...
902 if ( $authorised_value eq "branches" ) {
903 my $branches = GetBranchesLoop();
904 foreach my $thisbranch (@$branches) {
905 push @authorised_values, $thisbranch->{value};
906 $authorised_lib{ $thisbranch->{value} } = $thisbranch->{branchname};
908 } elsif ( $authorised_value eq "itemtypes" ) {
909 my $sth = $dbh->prepare("SELECT itemtype,description FROM itemtypes ORDER BY description");
910 $sth->execute;
911 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
912 push @authorised_values, $itemtype;
913 $authorised_lib{$itemtype} = $description;
915 } elsif ( $authorised_value eq "cn_source" ) {
916 my $class_sources = GetClassSources();
917 my $default_source = C4::Context->preference("DefaultClassificationSource");
918 foreach my $class_source ( sort keys %$class_sources ) {
919 next
920 unless $class_sources->{$class_source}->{'used'}
921 or ( $class_source eq $default_source );
922 push @authorised_values, $class_source;
923 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
925 } elsif ( $authorised_value eq "categorycode" ) {
926 my $sth = $dbh->prepare("SELECT categorycode, description FROM categories ORDER BY description");
927 $sth->execute;
928 while ( my ( $categorycode, $description ) = $sth->fetchrow_array ) {
929 push @authorised_values, $categorycode;
930 $authorised_lib{$categorycode} = $description;
933 #---- "true" authorised value
934 } else {
935 my $authorised_values_sth = $dbh->prepare("SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib");
937 $authorised_values_sth->execute($authorised_value);
939 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
940 push @authorised_values, $value;
941 $authorised_lib{$value} = $lib;
943 # For item location, we show the code and the libelle
944 $authorised_lib{$value} = $lib;
948 return (\@authorised_values, \%authorised_lib);
951 =head2 GetReservedAuthorisedValues
953 my %reserved_authorised_values = GetReservedAuthorisedValues();
955 Returns a hash containig all reserved words
957 =cut
959 sub GetReservedAuthorisedValues {
960 my %reserved_authorised_values =
961 map { $_ => 1 } ( 'date',
962 'branches',
963 'itemtypes',
964 'cn_source',
965 'categorycode',
966 'biblio_framework' );
968 return \%reserved_authorised_values;
972 =head2 IsAuthorisedValueValid
974 my $is_valid_ath_value = IsAuthorisedValueValid($authorised_value)
976 Returns 1 if $authorised_value is on the reserved authorised values list or
977 in the authorised value categories defined in
979 =cut
981 sub IsAuthorisedValueValid {
983 my $authorised_value = shift;
984 my $reserved_authorised_values = GetReservedAuthorisedValues();
986 if ( exists $reserved_authorised_values->{$authorised_value} ||
987 C4::Koha::IsAuthorisedValueCategory($authorised_value) ) {
988 return 1;
991 return 0;
994 =head2 GetParametersFromSQL
996 my @sql_parameters = GetParametersFromSQL($sql)
998 Returns an arrayref of hashes containing the keys name and authval
1000 =cut
1002 sub GetParametersFromSQL {
1004 my $sql = shift ;
1005 my @split = split(/<<|>>/,$sql);
1006 my @sql_parameters = ();
1008 for ( my $i = 0; $i < ($#split/2) ; $i++ ) {
1009 my ($name,$authval) = split(/\|/,$split[$i*2+1]);
1010 push @sql_parameters, { 'name' => $name, 'authval' => $authval };
1013 return \@sql_parameters;
1016 =head2 ValidateSQLParameters
1018 my @problematic_parameters = ValidateSQLParameters($sql)
1020 Returns an arrayref of hashes containing the keys name and authval of
1021 those SQL parameters that do not correspond to valid authorised names
1023 =cut
1025 sub ValidateSQLParameters {
1027 my $sql = shift;
1028 my @problematic_parameters = ();
1029 my $sql_parameters = GetParametersFromSQL($sql);
1031 foreach my $sql_parameter (@$sql_parameters) {
1032 if ( defined $sql_parameter->{'authval'} ) {
1033 push @problematic_parameters, $sql_parameter unless
1034 IsAuthorisedValueValid($sql_parameter->{'authval'});
1038 return \@problematic_parameters;
1042 __END__
1044 =head1 AUTHOR
1046 Chris Cormack <crc@liblime.com>
1048 =cut