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
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.
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.
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>.
23 use JSON
qw( from_json );
25 use vars
qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
27 use C4::Templates qw/themelanguage/;
34 use Koha::AuthorisedValues;
35 use Koha::Patron::Categories;
41 get_report_types get_report_areas get_report_groups get_columns build_query get_criteria
42 save_report get_saved_reports execute_query get_saved_report create_compound run_compound
43 get_column_type get_distinct_values save_dictionary get_from_dictionary
44 delete_definition delete_report format_results get_sql
46 GetReservedAuthorisedValues
48 IsAuthorisedValueValid
56 C4::Reports::Guided - Module for generating guided reports
60 use C4::Reports::Guided;
68 =head2 get_report_areas
70 This will return a list of all the available report areas
74 sub get_area_name_sql_snippet
{
76 [CIRC
=> "Circulation"],
79 [ACQ
=> "Acquisition"],
84 return "CASE report_area " .
85 join (" ", map "WHEN '$_->[0]' THEN '$_->[1]'", @REPORT_AREA) .
89 sub get_report_areas
{
91 my $report_areas = [ 'CIRC', 'CAT', 'PAT', 'ACQ', 'ACC', 'SER' ];
98 CIRC
=> [ 'borrowers', 'statistics', 'items', 'biblioitems' ],
99 CAT
=> [ 'items', 'biblioitems', 'biblio' ],
100 PAT
=> ['borrowers'],
101 ACQ
=> [ 'aqorders', 'biblio', 'items' ],
102 ACC
=> [ 'borrowers', 'accountlines' ],
103 SER
=> [ 'serial', 'serialitems', 'subscription', 'subscriptionhistory', 'subscriptionroutinglist', 'biblioitems', 'biblio', 'aqbooksellers' ],
107 =head2 get_report_types
109 This will return a list of all the available report types
113 sub get_report_types
{
114 my $dbh = C4
::Context
->dbh();
116 # FIXME these should be in the database perhaps
117 my @reports = ( 'Tabular', 'Summary', 'Matrix' );
119 for ( my $i = 0 ; $i < 3 ; $i++ ) {
121 $hashrep{id
} = $i + 1;
122 $hashrep{name
} = $reports[$i];
123 push @reports2, \
%hashrep;
125 return ( \
@reports2 );
129 =head2 get_report_groups
131 This will return a list of all the available report areas with groups
135 sub get_report_groups
{
136 my $dbh = C4
::Context
->dbh();
138 my $groups = GetAuthorisedValues
('REPORT_GROUP');
139 my $subgroups = GetAuthorisedValues
('REPORT_SUBGROUP');
141 my %groups_with_subgroups = map { $_->{authorised_value
} => {
145 foreach (@
$subgroups) {
146 my $sg = $_->{authorised_value
};
147 my $g = $_->{lib_opac
}
148 or warn( qq{REPORT_SUBGROUP
"$sg" without REPORT_GROUP
(lib_opac
)} ),
150 my $g_sg = $groups_with_subgroups{$g}
151 or warn( qq{REPORT_SUBGROUP
"$sg" with invalid REPORT_GROUP
"$g"} ),
153 $g_sg->{subgroups
}{$sg} = $_->{lib
};
155 return \
%groups_with_subgroups
158 =head2 get_all_tables
160 This will return a list of all tables in the database
165 my $dbh = C4
::Context
->dbh();
166 my $query = "SHOW TABLES";
167 my $sth = $dbh->prepare($query);
170 while ( my $data = $sth->fetchrow_arrayref() ) {
171 push @tables, $data->[0];
178 =head2 get_columns($area)
180 This will return a list of all columns for a report area
186 # this calls the internal function _get_columns
187 my ( $area, $cgi ) = @_;
188 my %table_areas = get_table_areas
;
189 my $tables = $table_areas{$area}
190 or die qq{Unsuported report area
"$area"};
194 foreach my $table (@
$tables) {
195 my @columns = _get_columns
($table,$cgi, $first);
197 push @allcolumns, @columns;
199 return ( \
@allcolumns );
203 my ($tablename,$cgi, $first) = @_;
204 my $dbh = C4
::Context
->dbh();
205 my $sth = $dbh->prepare("show columns from $tablename");
208 my $column_defs = _get_column_defs
($cgi);
210 $tablehash{'table'}=$tablename;
211 $tablehash{'__first__'} = $first;
212 push @columns, \
%tablehash;
213 while ( my $data = $sth->fetchrow_arrayref() ) {
215 $temphash{'name'} = "$tablename.$data->[0]";
216 $temphash{'description'} = $column_defs->{"$tablename.$data->[0]"};
217 push @columns, \
%temphash;
223 =head2 build_query($columns,$criteria,$orderby,$area)
225 This will build the sql needed to return the results asked for,
226 $columns is expected to be of the format tablename.columnname.
227 This is what get_columns returns.
232 my ( $columns, $criteria, $orderby, $area, $totals, $definition ) = @_;
235 CIRC
=> [ 'statistics.borrowernumber=borrowers.borrowernumber',
236 'items.itemnumber = statistics.itemnumber',
237 'biblioitems.biblioitemnumber = items.biblioitemnumber' ],
238 CAT
=> [ 'items.biblioitemnumber=biblioitems.biblioitemnumber',
239 'biblioitems.biblionumber=biblio.biblionumber' ],
241 ACQ
=> [ 'aqorders.biblionumber=biblio.biblionumber',
242 'biblio.biblionumber=items.biblionumber' ],
243 ACC
=> ['borrowers.borrowernumber=accountlines.borrowernumber'],
244 SER
=> [ 'serial.serialid=serialitems.serialid', 'serial.subscriptionid=subscription.subscriptionid', 'serial.subscriptionid=subscriptionhistory.subscriptionid', 'serial.subscriptionid=subscriptionroutinglist.subscriptionid', 'biblioitems.biblionumber=serial.biblionumber', 'biblio.biblionumber=biblioitems.biblionumber', 'subscription.aqbooksellerid=aqbooksellers.id'],
249 my $keys = $keys{$area};
250 my %table_areas = get_table_areas
;
251 my $tables = $table_areas{$area};
254 _build_query
( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition );
259 my ( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition) = @_;
261 # $keys is an array of joining constraints
262 my $dbh = C4
::Context
->dbh();
263 my $joinedtables = join( ',', @
$tables );
264 my $joinedcolumns = join( ',', @
$columns );
266 "SELECT $totals $joinedcolumns FROM $tables->[0] ";
267 for (my $i=1;$i<@
$tables;$i++){
268 $query .= "LEFT JOIN $tables->[$i] on ($keys->[$i-1]) ";
272 $criteria =~ s/AND/WHERE/;
273 $query .= " $criteria";
276 my @definitions = split(',',$definition);
278 foreach my $def (@definitions){
279 my $defin=get_from_dictionary
('',$def);
280 $deftext .=" ".$defin->[0]->{'saved_sql'};
282 if ($query =~ /WHERE/i){
286 $deftext =~ s/AND/WHERE/;
292 my @totcolumns = split( ',', $totals );
293 foreach my $total (@totcolumns) {
294 if ( $total =~ /\((.*)\)/ ) {
295 if ( $groupby eq '' ) {
296 $groupby = " GROUP BY $1";
311 =head2 get_criteria($area,$cgi);
313 Returns an arraref to hashrefs suitable for using in a tmpl_loop. With the criteria and available values.
318 my ($area,$cgi) = @_;
319 my $dbh = C4
::Context
->dbh();
321 # have to do someting here to know if its dropdown, free text, date etc
323 CIRC
=> [ 'statistics.type', 'borrowers.categorycode', 'statistics.branch',
324 'biblioitems.publicationyear|date', 'items.dateaccessioned|date' ],
325 CAT
=> [ 'items.itemnumber|textrange', 'items.biblionumber|textrange',
326 'items.barcode|textrange', 'biblio.frameworkcode',
327 'items.holdingbranch', 'items.homebranch',
328 'biblio.datecreated|daterange', 'biblio.timestamp|daterange',
329 'items.onloan|daterange', 'items.ccode',
330 'items.itemcallnumber|textrange', 'items.itype', 'items.itemlost',
332 PAT
=> [ 'borrowers.branchcode', 'borrowers.categorycode' ],
333 ACQ
=> ['aqorders.datereceived|date'],
334 ACC
=> [ 'borrowers.branchcode', 'borrowers.categorycode' ],
335 SER
=> ['subscription.startdate|date', 'subscription.enddate|date', 'subscription.periodicity', 'subscription.callnumber', 'subscription.location', 'subscription.branchcode'],
338 # Adds itemtypes to criteria, according to the syspref
339 if ( C4
::Context
->preference('item-level_itypes') ) {
340 unshift @
{ $criteria{'CIRC'} }, 'items.itype';
341 unshift @
{ $criteria{'CAT'} }, 'items.itype';
343 unshift @
{ $criteria{'CIRC'} }, 'biblioitems.itemtype';
344 unshift @
{ $criteria{'CAT'} }, 'biblioitems.itemtype';
348 my $crit = $criteria{$area};
349 my $column_defs = _get_column_defs
($cgi);
351 foreach my $localcrit (@
$crit) {
352 my ( $value, $type ) = split( /\|/, $localcrit );
353 my ( $table, $column ) = split( /\./, $value );
354 if ($type eq 'textrange') {
356 $temp{'name'} = $value;
357 $temp{'from'} = "from_" . $value;
358 $temp{'to'} = "to_" . $value;
359 $temp{'textrange'} = 1;
360 $temp{'description'} = $column_defs->{$value};
361 push @criteria_array, \
%temp;
363 elsif ($type eq 'date') {
365 $temp{'name'} = $value;
367 $temp{'description'} = $column_defs->{$value};
368 push @criteria_array, \
%temp;
370 elsif ($type eq 'daterange') {
372 $temp{'name'} = $value;
373 $temp{'from'} = "from_" . $value;
374 $temp{'to'} = "to_" . $value;
375 $temp{'daterange'} = 1;
376 $temp{'description'} = $column_defs->{$value};
377 push @criteria_array, \
%temp;
381 "SELECT distinct($column) as availablevalues FROM $table";
382 my $sth = $dbh->prepare($query);
385 # push the runtime choosing option
387 $list='branches' if $column eq 'branchcode' or $column eq 'holdingbranch' or $column eq 'homebranch';
388 $list='categorycode' if $column eq 'categorycode';
389 $list='itemtypes' if $column eq 'itype';
390 $list='ccode' if $column eq 'ccode';
391 # TODO : improve to let the librarian choose the description at runtime
393 availablevalues
=> "<<$column" . ( $list ?
"|$list" : '' ) . ">>",
394 display_value
=> "<<$column" . ( $list ?
"|$list" : '' ) . ">>",
396 while ( my $row = $sth->fetchrow_hashref() ) {
397 if ($row->{'availablevalues'} eq '') { $row->{'default'} = 1 }
398 else { $row->{display_value
} = _get_display_value
( $row->{'availablevalues'}, $column ); }
404 $temp{'name'} = $value;
405 $temp{'description'} = $column_defs->{$value};
406 $temp{'values'} = \
@values;
408 push @criteria_array, \
%temp;
411 return ( \
@criteria_array );
415 my $sql = shift or return;
416 my $sth = C4
::Context
->dbh->prepare($sql);
418 my $rows = $sth->fetchall_arrayref();
419 return scalar (@
$rows);
424 ($sth, $error) = execute_query($sql, $offset, $limit[, \@sql_params])
427 This function returns a DBI statement handler from which the caller can
428 fetch the results of the SQL passed via C<$sql>.
430 If passed any query other than a SELECT, or if there is a DB error,
431 C<$errors> is returned, and is a hashref containing the error after this
434 C<$error->{'sqlerr'}> contains the offending SQL keyword.
435 C<$error->{'queryerr'}> contains the native db engine error returned
438 C<$offset>, and C<$limit> are required parameters.
440 C<\@sql_params> is an optional list of parameter values to paste in.
441 The caller is responsible for making sure that C<$sql> has placeholders
442 and that the number placeholders matches the number of parameters.
446 # returns $sql, $offset, $limit
447 # $sql returned will be transformed to:
448 # ~ remove any LIMIT clause
449 # ~ repace SELECT clause w/ SELECT count(*)
451 sub select_2_select_count
{
452 # Modify the query passed in to create a count query... (I think this covers all cases -crn)
453 my ($sql) = strip_limit
(shift) or return;
454 $sql =~ s/\bSELECT\W+(?:\w+\W+){1,}?FROM\b|\bSELECT\W\*\WFROM\b/SELECT count(*) FROM /ig;
458 # This removes the LIMIT from the query so that a custom one can be specified.
460 # ($new_sql, $offset, $limit) = strip_limit($sql);
463 # $sql is the query to modify
464 # $new_sql is the resulting query
465 # $offset is the offset value, if the LIMIT was the two-argument form,
466 # 0 if it wasn't otherwise given.
467 # $limit is the limit value
470 # * This makes an effort to not break subqueries that have their own
471 # LIMIT specified. It does that by only removing a LIMIT if it comes after
472 # a WHERE clause (which isn't perfect, but at least should make more cases
473 # work - subqueries with a limit in the WHERE will still break.)
474 # * If your query doesn't have a WHERE clause then all LIMITs will be
475 # removed. This may break some subqueries, but is hopefully rare enough
476 # to not be a big issue.
481 return ($sql, 0, undef) unless $sql =~ /\bLIMIT\b/i;
483 # Two options: if there's no WHERE clause in the SQL, we simply capture
484 # any LIMIT that's there. If there is a WHERE, we make sure that we only
485 # capture a LIMIT after the last one. This prevents stomping on subqueries.
486 if ($sql !~ /\bWHERE\b/i) {
487 (my $res = $sql) =~ s/\bLIMIT\b\s*(\d+)(\s*\,\s*(\d+))?\s*/ /ig;
488 return ($res, (defined $2 ?
$1 : 0), (defined $3 ?
$3 : $1));
491 $res =~ m/.*\bWHERE\b/gsi;
492 $res =~ s/\G(.*)\bLIMIT\b\s*(\d+)(\s*\,\s*(\d+))?\s*/$1 /is;
493 return ($res, (defined $3 ?
$2 : 0), (defined $4 ?
$4 : $2));
499 my ( $sql, $offset, $limit, $sql_params, $report_id ) = @_;
501 $sql_params = [] unless defined $sql_params;
505 carp
"execute_query() called without SQL argument";
508 $offset = 0 unless $offset;
509 $limit = 999999 unless $limit;
510 $debug and print STDERR
"execute_query($sql, $offset, $limit)\n";
511 if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
512 return (undef, { sqlerr
=> $1} );
513 } elsif ($sql !~ /^\s*SELECT\b\s*/i) {
514 return (undef, { queryerr
=> 'Missing SELECT'} );
517 my ($useroffset, $userlimit);
519 # Grab offset/limit from user supplied LIMIT and drop the LIMIT so we can control pagination
520 ($sql, $useroffset, $userlimit) = strip_limit
($sql);
521 $debug and warn sprintf "User has supplied (OFFSET,) LIMIT = %s, %s",
523 (defined($userlimit ) ?
$userlimit : 'UNDEF');
524 $offset += $useroffset;
525 if (defined($userlimit)) {
526 if ($offset + $limit > $userlimit ) {
527 $limit = $userlimit - $offset;
528 } elsif ( ! $offset && $limit < $userlimit ) {
532 $sql .= " LIMIT ?, ?";
534 my $dbh = C4
::Context
->dbh;
536 $dbh->do( 'UPDATE saved_sql SET last_run = NOW() WHERE id = ?', undef, $report_id ) if $report_id;
538 my $sth = $dbh->prepare($sql);
539 $sth->execute(@
$sql_params, $offset, $limit);
541 return ( $sth, { queryerr
=> $sth->errstr } ) if ($sth->err);
545 =head2 save_report($sql,$name,$type,$notes)
547 Given some sql and a name this will saved it so that it can reused
548 Returns id of the newly created report
554 my $borrowernumber = $fields->{borrowernumber
};
555 my $sql = $fields->{sql
};
556 my $name = $fields->{name
};
557 my $type = $fields->{type
};
558 my $notes = $fields->{notes
};
559 my $area = $fields->{area
};
560 my $group = $fields->{group
};
561 my $subgroup = $fields->{subgroup
};
562 my $cache_expiry = $fields->{cache_expiry
} || 300;
563 my $public = $fields->{public
};
565 my $dbh = C4
::Context
->dbh();
566 $sql =~ s/(\s*\;\s*)$//; # removes trailing whitespace and /;/
567 my $query = "INSERT INTO saved_sql (borrowernumber,date_created,last_modified,savedsql,report_name,report_area,report_group,report_subgroup,type,notes,cache_expiry,public) VALUES (?,now(),now(),?,?,?,?,?,?,?,?,?)";
568 $dbh->do($query, undef, $borrowernumber, $sql, $name, $area, $group, $subgroup, $type, $notes, $cache_expiry, $public);
570 my $id = $dbh->selectrow_array("SELECT max(id) FROM saved_sql WHERE borrowernumber=? AND report_name=?", undef,
571 $borrowernumber, $name);
576 my $id = shift || croak
"No Id given";
578 my $sql = $fields->{sql
};
579 my $name = $fields->{name
};
580 my $notes = $fields->{notes
};
581 my $group = $fields->{group
};
582 my $subgroup = $fields->{subgroup
};
583 my $cache_expiry = $fields->{cache_expiry
};
584 my $public = $fields->{public
};
586 if( $cache_expiry >= 2592000 ){
587 die "Please specify a cache expiry less than 30 days\n";
590 my $dbh = C4
::Context
->dbh();
591 $sql =~ s/(\s*\;\s*)$//; # removes trailing whitespace and /;/
592 my $query = "UPDATE saved_sql SET savedsql = ?, last_modified = now(), report_name = ?, report_group = ?, report_subgroup = ?, notes = ?, cache_expiry = ?, public = ? WHERE id = ? ";
593 $dbh->do($query, undef, $sql, $name, $group, $subgroup, $notes, $cache_expiry, $public, $id );
597 my ( $id, $json ) = @_;
598 my $dbh = C4
::Context
->dbh();
600 INSERT INTO saved_reports
( report_id
, report
, date_run
) VALUES
( ?
, ?
, NOW
() );
601 |, undef, $id, $json );
606 my $dbh = C4
::Context
->dbh();
607 my ( $report_name, $notes, $json, $date_run ) = $dbh->selectrow_array(q
|
608 SELECT ss
.report_name
, ss
.notes
, sr
.report
, sr
.date_run
610 LEFT JOIN saved_reports sr ON sr
.report_id
= ss
.id
614 report_name
=> $report_name,
616 results
=> from_json
( $json ),
617 date_run
=> $date_run,
624 foreach my $id (@ids) {
625 my $data = get_saved_report
($id);
626 logaction
( "REPORTS", "DELETE", $id, "$data->{'report_name'} | $data->{'savedsql'} " ) if C4
::Context
->preference("ReportsLog");
628 my $dbh = C4
::Context
->dbh;
629 my $query = 'DELETE FROM saved_sql WHERE id IN (' . join( ',', ('?') x
@ids ) . ')';
630 my $sth = $dbh->prepare($query);
631 return $sth->execute(@ids);
634 sub get_saved_reports_base_query
{
635 my $area_name_sql_snippet = get_area_name_sql_snippet
;
637 SELECT s.*, $area_name_sql_snippet, av_g.lib AS groupname, av_sg.lib AS subgroupname,
638 b.firstname AS borrowerfirstname, b.surname AS borrowersurname
640 LEFT JOIN saved_reports r ON r.report_id = s.id
641 LEFT OUTER JOIN authorised_values av_g ON (av_g.category = 'REPORT_GROUP' AND av_g.authorised_value = s.report_group)
642 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)
643 LEFT OUTER JOIN borrowers b USING (borrowernumber)
647 sub get_saved_reports
{
648 # $filter is either { date => $d, author => $a, keyword => $kw, }
649 # or $keyword. Optional.
651 $filter = { keyword
=> $filter } if $filter && !ref( $filter );
652 my ($group, $subgroup) = @_;
654 my $dbh = C4
::Context
->dbh();
655 my $query = get_saved_reports_base_query
;
658 if (my $date = $filter->{date
}) {
659 $date = eval { output_pref
( { dt
=> dt_from_string
( $date ), dateonly
=> 1, dateformat
=> 'iso' }); };
660 push @cond, "DATE(last_modified) = ? OR
662 push @args, $date, $date, $date;
664 if (my $author = $filter->{author
}) {
665 $author = "%$author%";
666 push @cond, "surname LIKE ? OR
668 push @args, $author, $author;
670 if (my $keyword = $filter->{keyword
}) {
673 OR report_name LIKE ?
678 push @args, "%$keyword%", "%$keyword%", "%$keyword%", "%$keyword%", $keyword;
680 if ($filter->{group
}) {
681 push @cond, "report_group = ?";
682 push @args, $filter->{group
};
684 if ($filter->{subgroup
}) {
685 push @cond, "report_subgroup = ?";
686 push @args, $filter->{subgroup
};
689 $query .= " WHERE ".join( " AND ", map "($_)", @cond ) if @cond;
690 $query .= " ORDER by date_created";
692 my $result = $dbh->selectall_arrayref($query, {Slice
=> {}}, @args);
697 sub get_saved_report
{
698 my $dbh = C4
::Context
->dbh();
701 if ($#_ == 0 && ref $_[0] ne 'HASH') {
703 $query = " SELECT * FROM saved_sql WHERE id = ?";
704 } elsif (ref $_[0] eq 'HASH') {
706 if ($selector->{name
}) {
707 $query = " SELECT * FROM saved_sql WHERE report_name = ?";
708 $report_arg = $selector->{name
};
709 } elsif ($selector->{id
} || $selector->{id
} eq '0') {
710 $query = " SELECT * FROM saved_sql WHERE id = ?";
711 $report_arg = $selector->{id
};
718 return $dbh->selectrow_hashref($query, undef, $report_arg);
721 =head2 create_compound($masterID,$subreportID)
723 This will take 2 reports and create a compound report using both of them
727 sub create_compound
{
728 my ( $masterID, $subreportID ) = @_;
729 my $dbh = C4
::Context
->dbh();
732 my $master = get_saved_report
($masterID);
733 my $mastersql = $master->{savedsql
};
734 my $mastertype = $master->{type
};
735 my $sub = get_saved_report
($subreportID);
736 my $subsql = $master->{savedsql
};
737 my $subtype = $master->{type
};
739 # now we have to do some checking to see how these two will fit together
741 my ( $mastertables, $subtables );
742 if ( $mastersql =~ / from (.*) where /i ) {
745 if ( $subsql =~ / from (.*) where /i ) {
748 return ( $mastertables, $subtables );
751 =head2 get_column_type($column)
753 This takes a column name of the format table.column and will return what type it is
754 (free text, set values, date)
758 sub get_column_type
{
759 my ($tablecolumn) = @_;
760 my ($table,$column) = split(/\./,$tablecolumn);
761 my $dbh = C4
::Context
->dbh();
765 # mysql doesn't support a column selection, set column to %
767 my $sth = $dbh->column_info( $catalog, $schema, $table, $tempcolumn ) || die $dbh->errstr;
768 while (my $info = $sth->fetchrow_hashref()){
769 if ($info->{'COLUMN_NAME'} eq $column){
771 if ($info->{'TYPE_NAME'} eq 'CHAR' || $info->{'TYPE_NAME'} eq 'VARCHAR'){
772 $info->{'TYPE_NAME'} = 'distinct';
774 return $info->{'TYPE_NAME'};
779 =head2 get_distinct_values($column)
781 Given a column name, return an arrary ref of hashrefs suitable for use as a tmpl_loop
782 with the distinct values of the column
786 sub get_distinct_values
{
787 my ($tablecolumn) = @_;
788 my ($table,$column) = split(/\./,$tablecolumn);
789 my $dbh = C4
::Context
->dbh();
791 "SELECT distinct($column) as availablevalues FROM $table";
792 my $sth = $dbh->prepare($query);
794 return $sth->fetchall_arrayref({});
797 sub save_dictionary
{
798 my ( $name, $description, $sql, $area ) = @_;
799 my $dbh = C4
::Context
->dbh();
800 my $query = "INSERT INTO reports_dictionary (name,description,saved_sql,report_area,date_created,date_modified)
801 VALUES (?,?,?,?,now(),now())";
802 my $sth = $dbh->prepare($query);
803 $sth->execute($name,$description,$sql,$area) || return 0;
807 sub get_from_dictionary
{
808 my ( $area, $id ) = @_;
809 my $dbh = C4
::Context
->dbh();
810 my $area_name_sql_snippet = get_area_name_sql_snippet
;
812 SELECT d.*, $area_name_sql_snippet
813 FROM reports_dictionary d
817 $query .= " WHERE report_area = ?";
819 $query .= " WHERE id = ?";
821 my $sth = $dbh->prepare($query);
825 $sth->execute($area);
830 while ( my $data = $sth->fetchrow_hashref() ) {
836 sub delete_definition
{
837 my ($id) = @_ or return;
838 my $dbh = C4
::Context
->dbh();
839 my $query = "DELETE FROM reports_dictionary WHERE id = ?";
840 my $sth = $dbh->prepare($query);
845 my ($id) = @_ or return;
846 my $dbh = C4
::Context
->dbh();
847 my $query = "SELECT * FROM saved_sql WHERE id = ?";
848 my $sth = $dbh->prepare($query);
850 my $data=$sth->fetchrow_hashref();
851 return $data->{'savedsql'};
855 my ( $report_id ) = @_;
856 my $dbh = C4
::Context
->dbh;
858 return $dbh->selectall_arrayref(q
|
859 SELECT id
, report
, date_run
862 |, { Slice
=> {} }, $report_id);
865 sub _get_column_defs
{
868 my $columns_def_file = "columns.def";
869 my $htdocs = C4
::Context
->config('intrahtdocs');
870 my $section = 'intranet';
872 # We need the theme and the lang
873 # Since columns.def is not in the modules directory, we cannot sent it for the $tmpl var
874 my ($theme, $lang, $availablethemes) = C4
::Templates
::themelanguage
($htdocs, 'about.tt', $section, $cgi);
876 my $full_path_to_columns_def_file="$htdocs/$theme/$lang/$columns_def_file";
877 open (my $fh, '<:encoding(utf-8)', $full_path_to_columns_def_file);
878 while ( my $input = <$fh> ){
880 if ( $input =~ m
|<field name
="(.*)">(.*)</field
>| ) {
881 my ( $field, $translation ) = ( $1, $2 );
882 $columns{$field} = $translation;
889 =head2 GetReservedAuthorisedValues
891 my %reserved_authorised_values = GetReservedAuthorisedValues();
893 Returns a hash containig all reserved words
897 sub GetReservedAuthorisedValues
{
898 my %reserved_authorised_values =
899 map { $_ => 1 } ( 'date',
904 'biblio_framework' );
906 return \
%reserved_authorised_values;
910 =head2 IsAuthorisedValueValid
912 my $is_valid_ath_value = IsAuthorisedValueValid($authorised_value)
914 Returns 1 if $authorised_value is on the reserved authorised values list or
915 in the authorised value categories defined in
919 sub IsAuthorisedValueValid
{
921 my $authorised_value = shift;
922 my $reserved_authorised_values = GetReservedAuthorisedValues
();
924 if ( exists $reserved_authorised_values->{$authorised_value} ||
925 Koha
::AuthorisedValues
->search({ category
=> $authorised_value })->count ) {
932 =head2 GetParametersFromSQL
934 my @sql_parameters = GetParametersFromSQL($sql)
936 Returns an arrayref of hashes containing the keys name and authval
940 sub GetParametersFromSQL
{
943 my @split = split(/<<|>>/,$sql);
944 my @sql_parameters = ();
946 for ( my $i = 0; $i < ($#split/2) ; $i++ ) {
947 my ($name,$authval) = split(/\|/,$split[$i*2+1]);
948 push @sql_parameters, { 'name' => $name, 'authval' => $authval };
951 return \
@sql_parameters;
954 =head2 ValidateSQLParameters
956 my @problematic_parameters = ValidateSQLParameters($sql)
958 Returns an arrayref of hashes containing the keys name and authval of
959 those SQL parameters that do not correspond to valid authorised names
963 sub ValidateSQLParameters
{
966 my @problematic_parameters = ();
967 my $sql_parameters = GetParametersFromSQL
($sql);
969 foreach my $sql_parameter (@
$sql_parameters) {
970 if ( defined $sql_parameter->{'authval'} ) {
971 push @problematic_parameters, $sql_parameter unless
972 IsAuthorisedValueValid
($sql_parameter->{'authval'});
976 return \
@problematic_parameters;
979 sub _get_display_value
{
980 my ( $original_value, $column ) = @_;
981 if ( $column eq 'periodicity' ) {
982 my $dbh = C4
::Context
->dbh();
983 my $query = "SELECT description FROM subscription_frequencies WHERE id = ?";
984 my $sth = $dbh->prepare($query);
985 $sth->execute($original_value);
986 return $sth->fetchrow;
988 return $original_value;
996 Chris Cormack <crc@liblime.com>