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>.
24 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
26 use C4::Templates qw/themelanguage/;
35 use Koha::AuthorisedValues;
36 use Koha::Patron::Categories;
42 get_report_types get_report_areas get_report_groups get_columns build_query get_criteria
43 save_report get_saved_reports execute_query get_saved_report create_compound run_compound
44 get_column_type get_distinct_values save_dictionary get_from_dictionary
45 delete_definition delete_report format_results get_sql
47 GetReservedAuthorisedValues
49 IsAuthorisedValueValid
57 C4::Reports::Guided - Module for generating guided reports
61 use C4::Reports::Guided;
69 =head2 get_report_areas
71 This will return a list of all the available report areas
75 sub get_area_name_sql_snippet {
77 [CIRC => "Circulation"],
80 [ACQ => "Acquisition"],
85 return "CASE report_area " .
86 join (" ", map "WHEN '$_->[0]' THEN '$_->[1]'", @REPORT_AREA) .
90 sub get_report_areas {
92 my $report_areas = [ 'CIRC', 'CAT', 'PAT', 'ACQ', 'ACC', 'SER' ];
99 CIRC => [ 'borrowers', 'statistics', 'items', 'biblioitems' ],
100 CAT => [ 'items', 'biblioitems', 'biblio' ],
101 PAT => ['borrowers'],
102 ACQ => [ 'aqorders', 'biblio', 'items' ],
103 ACC => [ 'borrowers', 'accountlines' ],
104 SER => [ 'serial', 'serialitems', 'subscription', 'subscriptionhistory', 'subscriptionroutinglist', 'biblioitems', 'biblio', 'aqbooksellers' ],
108 =head2 get_report_types
110 This will return a list of all the available report types
114 sub get_report_types {
115 my $dbh = C4::Context->dbh();
117 # FIXME these should be in the database perhaps
118 my @reports = ( 'Tabular', 'Summary', 'Matrix' );
120 for ( my $i = 0 ; $i < 3 ; $i++ ) {
122 $hashrep{id} = $i + 1;
123 $hashrep{name} = $reports[$i];
124 push @reports2, \%hashrep;
126 return ( \@reports2 );
130 =head2 get_report_groups
132 This will return a list of all the available report areas with groups
136 sub get_report_groups {
137 my $dbh = C4::Context->dbh();
139 my $groups = GetAuthorisedValues('REPORT_GROUP');
140 my $subgroups = GetAuthorisedValues('REPORT_SUBGROUP');
142 my %groups_with_subgroups = map { $_->{authorised_value} => {
146 foreach (@$subgroups) {
147 my $sg = $_->{authorised_value};
148 my $g = $_->{lib_opac}
149 or warn( qq{REPORT_SUBGROUP "$sg" without REPORT_GROUP (lib_opac)} ),
151 my $g_sg = $groups_with_subgroups{$g}
152 or warn( qq{REPORT_SUBGROUP "$sg" with invalid REPORT_GROUP "$g"} ),
154 $g_sg->{subgroups}{$sg} = $_->{lib};
156 return \%groups_with_subgroups
159 =head2 get_all_tables
161 This will return a list of all tables in the database
166 my $dbh = C4::Context->dbh();
167 my $query = "SHOW TABLES";
168 my $sth = $dbh->prepare($query);
171 while ( my $data = $sth->fetchrow_arrayref() ) {
172 push @tables, $data->[0];
179 =head2 get_columns($area)
181 This will return a list of all columns for a report area
187 # this calls the internal function _get_columns
188 my ( $area, $cgi ) = @_;
189 my %table_areas = get_table_areas;
190 my $tables = $table_areas{$area}
191 or die qq{Unsuported report area "$area"};
195 foreach my $table (@$tables) {
196 my @columns = _get_columns($table,$cgi, $first);
198 push @allcolumns, @columns;
200 return ( \@allcolumns );
204 my ($tablename,$cgi, $first) = @_;
205 my $dbh = C4::Context->dbh();
206 my $sth = $dbh->prepare("show columns from $tablename");
209 my $column_defs = _get_column_defs($cgi);
211 $tablehash{'table'}=$tablename;
212 $tablehash{'__first__'} = $first;
213 push @columns, \%tablehash;
214 while ( my $data = $sth->fetchrow_arrayref() ) {
216 $temphash{'name'} = "$tablename.$data->[0]";
217 $temphash{'description'} = $column_defs->{"$tablename.$data->[0]"};
218 push @columns, \%temphash;
224 =head2 build_query($columns,$criteria,$orderby,$area)
226 This will build the sql needed to return the results asked for,
227 $columns is expected to be of the format tablename.columnname.
228 This is what get_columns returns.
233 my ( $columns, $criteria, $orderby, $area, $totals, $definition ) = @_;
236 CIRC => [ 'statistics.borrowernumber=borrowers.borrowernumber',
237 'items.itemnumber = statistics.itemnumber',
238 'biblioitems.biblioitemnumber = items.biblioitemnumber' ],
239 CAT => [ 'items.biblioitemnumber=biblioitems.biblioitemnumber',
240 'biblioitems.biblionumber=biblio.biblionumber' ],
242 ACQ => [ 'aqorders.biblionumber=biblio.biblionumber',
243 'biblio.biblionumber=items.biblionumber' ],
244 ACC => ['borrowers.borrowernumber=accountlines.borrowernumber'],
245 SER => [ 'serial.serialid=serialitems.serialid', 'serial.subscriptionid=subscription.subscriptionid', 'serial.subscriptionid=subscriptionhistory.subscriptionid', 'serial.subscriptionid=subscriptionroutinglist.subscriptionid', 'biblioitems.biblionumber=serial.biblionumber', 'biblio.biblionumber=biblioitems.biblionumber', 'subscription.aqbooksellerid=aqbooksellers.id'],
250 my $keys = $keys{$area};
251 my %table_areas = get_table_areas;
252 my $tables = $table_areas{$area};
255 _build_query( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition );
260 my ( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition) = @_;
262 # $keys is an array of joining constraints
263 my $dbh = C4::Context->dbh();
264 my $joinedtables = join( ',', @$tables );
265 my $joinedcolumns = join( ',', @$columns );
267 "SELECT $totals $joinedcolumns FROM $tables->[0] ";
268 for (my $i=1;$i<@$tables;$i++){
269 $query .= "LEFT JOIN $tables->[$i] on ($keys->[$i-1]) ";
273 $criteria =~ s/AND/WHERE/;
274 $query .= " $criteria";
277 my @definitions = split(',',$definition);
279 foreach my $def (@definitions){
280 my $defin=get_from_dictionary('',$def);
281 $deftext .=" ".$defin->[0]->{'saved_sql'};
283 if ($query =~ /WHERE/i){
287 $deftext =~ s/AND/WHERE/;
293 my @totcolumns = split( ',', $totals );
294 foreach my $total (@totcolumns) {
295 if ( $total =~ /\((.*)\)/ ) {
296 if ( $groupby eq '' ) {
297 $groupby = " GROUP BY $1";
312 =head2 get_criteria($area,$cgi);
314 Returns an arraref to hashrefs suitable for using in a tmpl_loop. With the criteria and available values.
319 my ($area,$cgi) = @_;
320 my $dbh = C4::Context->dbh();
322 # have to do someting here to know if its dropdown, free text, date etc
324 CIRC => [ 'statistics.type', 'borrowers.categorycode', 'statistics.branch',
325 'biblioitems.publicationyear|date', 'items.dateaccessioned|date' ],
326 CAT => [ 'items.itemnumber|textrange', 'items.biblionumber|textrange',
327 'items.barcode|textrange', 'biblio.frameworkcode',
328 'items.holdingbranch', 'items.homebranch',
329 'biblio.datecreated|daterange', 'biblio.timestamp|daterange',
330 'items.onloan|daterange', 'items.ccode',
331 'items.itemcallnumber|textrange', 'items.itype', 'items.itemlost',
333 PAT => [ 'borrowers.branchcode', 'borrowers.categorycode' ],
334 ACQ => ['aqorders.datereceived|date'],
335 ACC => [ 'borrowers.branchcode', 'borrowers.categorycode' ],
336 SER => ['subscription.startdate|date', 'subscription.enddate|date', 'subscription.periodicity', 'subscription.callnumber', 'subscription.location', 'subscription.branchcode'],
339 # Adds itemtypes to criteria, according to the syspref
340 if ( C4::Context->preference('item-level_itypes') ) {
341 unshift @{ $criteria{'CIRC'} }, 'items.itype';
342 unshift @{ $criteria{'CAT'} }, 'items.itype';
344 unshift @{ $criteria{'CIRC'} }, 'biblioitems.itemtype';
345 unshift @{ $criteria{'CAT'} }, 'biblioitems.itemtype';
349 my $crit = $criteria{$area};
350 my $column_defs = _get_column_defs($cgi);
352 foreach my $localcrit (@$crit) {
353 my ( $value, $type ) = split( /\|/, $localcrit );
354 my ( $table, $column ) = split( /\./, $value );
355 if ($type eq 'textrange') {
357 $temp{'name'} = $value;
358 $temp{'from'} = "from_" . $value;
359 $temp{'to'} = "to_" . $value;
360 $temp{'textrange'} = 1;
361 $temp{'description'} = $column_defs->{$value};
362 push @criteria_array, \%temp;
364 elsif ($type eq 'date') {
366 $temp{'name'} = $value;
368 $temp{'description'} = $column_defs->{$value};
369 push @criteria_array, \%temp;
371 elsif ($type eq 'daterange') {
373 $temp{'name'} = $value;
374 $temp{'from'} = "from_" . $value;
375 $temp{'to'} = "to_" . $value;
376 $temp{'daterange'} = 1;
377 $temp{'description'} = $column_defs->{$value};
378 push @criteria_array, \%temp;
382 "SELECT distinct($column) as availablevalues FROM $table";
383 my $sth = $dbh->prepare($query);
386 # push the runtime choosing option
388 $list='branches' if $column eq 'branchcode' or $column eq 'holdingbranch' or $column eq 'homebranch';
389 $list='categorycode' if $column eq 'categorycode';
390 $list='itemtypes' if $column eq 'itype';
391 $list='ccode' if $column eq 'ccode';
392 # TODO : improve to let the librarian choose the description at runtime
394 availablevalues => "<<$column" . ( $list ? "|$list" : '' ) . ">>",
395 display_value => "<<$column" . ( $list ? "|$list" : '' ) . ">>",
397 while ( my $row = $sth->fetchrow_hashref() ) {
398 if ($row->{'availablevalues'} eq '') { $row->{'default'} = 1 }
399 else { $row->{display_value} = _get_display_value( $row->{'availablevalues'}, $column ); }
405 $temp{'name'} = $value;
406 $temp{'description'} = $column_defs->{$value};
407 $temp{'values'} = \@values;
409 push @criteria_array, \%temp;
412 return ( \@criteria_array );
416 my $sql = shift or return;
417 my $sth = C4::Context->dbh->prepare($sql);
419 my $rows = $sth->fetchall_arrayref();
420 return scalar (@$rows);
425 ($sth, $error) = execute_query($sql, $offset, $limit[, \@sql_params])
428 This function returns a DBI statement handler from which the caller can
429 fetch the results of the SQL passed via C<$sql>.
431 If passed any query other than a SELECT, or if there is a DB error,
432 C<$errors> is returned, and is a hashref containing the error after this
435 C<$error->{'sqlerr'}> contains the offending SQL keyword.
436 C<$error->{'queryerr'}> contains the native db engine error returned
439 C<$offset>, and C<$limit> are required parameters.
441 C<\@sql_params> is an optional list of parameter values to paste in.
442 The caller is responsible for making sure that C<$sql> has placeholders
443 and that the number placeholders matches the number of parameters.
447 # returns $sql, $offset, $limit
448 # $sql returned will be transformed to:
449 # ~ remove any LIMIT clause
450 # ~ repace SELECT clause w/ SELECT count(*)
452 sub select_2_select_count {
453 # Modify the query passed in to create a count query... (I think this covers all cases -crn)
454 my ($sql) = strip_limit(shift) or return;
455 $sql =~ s/\bSELECT\W+(?:\w+\W+){1,}?FROM\b|\bSELECT\W\*\WFROM\b/SELECT count(*) FROM /ig;
459 # This removes the LIMIT from the query so that a custom one can be specified.
461 # ($new_sql, $offset, $limit) = strip_limit($sql);
464 # $sql is the query to modify
465 # $new_sql is the resulting query
466 # $offset is the offset value, if the LIMIT was the two-argument form,
467 # 0 if it wasn't otherwise given.
468 # $limit is the limit value
471 # * This makes an effort to not break subqueries that have their own
472 # LIMIT specified. It does that by only removing a LIMIT if it comes after
473 # a WHERE clause (which isn't perfect, but at least should make more cases
474 # work - subqueries with a limit in the WHERE will still break.)
475 # * If your query doesn't have a WHERE clause then all LIMITs will be
476 # removed. This may break some subqueries, but is hopefully rare enough
477 # to not be a big issue.
482 return ($sql, 0, undef) unless $sql =~ /\bLIMIT\b/i;
484 # Two options: if there's no WHERE clause in the SQL, we simply capture
485 # any LIMIT that's there. If there is a WHERE, we make sure that we only
486 # capture a LIMIT after the last one. This prevents stomping on subqueries.
487 if ($sql !~ /\bWHERE\b/i) {
488 (my $res = $sql) =~ s/\bLIMIT\b\s*(\d+)(\s*\,\s*(\d+))?\s*/ /ig;
489 return ($res, (defined $2 ? $1 : 0), (defined $3 ? $3 : $1));
492 $res =~ m/.*\bWHERE\b/gsi;
493 $res =~ s/\G(.*)\bLIMIT\b\s*(\d+)(\s*\,\s*(\d+))?\s*/$1 /is;
494 return ($res, (defined $3 ? $2 : 0), (defined $4 ? $4 : $2));
500 my ( $sql, $offset, $limit, $sql_params ) = @_;
502 $sql_params = [] unless defined $sql_params;
506 carp "execute_query() called without SQL argument";
509 $offset = 0 unless $offset;
510 $limit = 999999 unless $limit;
511 $debug and print STDERR "execute_query($sql, $offset, $limit)\n";
512 if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
513 return (undef, { sqlerr => $1} );
514 } elsif ($sql !~ /^\s*SELECT\b\s*/i) {
515 return (undef, { queryerr => 'Missing SELECT'} );
518 my ($useroffset, $userlimit);
520 # Grab offset/limit from user supplied LIMIT and drop the LIMIT so we can control pagination
521 ($sql, $useroffset, $userlimit) = strip_limit($sql);
522 $debug and warn sprintf "User has supplied (OFFSET,) LIMIT = %s, %s",
524 (defined($userlimit ) ? $userlimit : 'UNDEF');
525 $offset += $useroffset;
526 if (defined($userlimit)) {
527 if ($offset + $limit > $userlimit ) {
528 $limit = $userlimit - $offset;
529 } elsif ( ! $offset && $limit < $userlimit ) {
533 $sql .= " LIMIT ?, ?";
535 my $sth = C4::Context->dbh->prepare($sql);
536 $sth->execute(@$sql_params, $offset, $limit);
537 return ( $sth, { queryerr => $sth->errstr } ) if ($sth->err);
539 # my @xmlarray = ... ;
540 # my $url = "/cgi-bin/koha/reports/guided_reports.pl?phase=retrieve%20results&id=$id";
541 # my $xml = XML::Dumper->new()->pl2xml( \@xmlarray );
542 # store_results($id,$xml);
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 );
598 my $dbh = C4::Context->dbh();
599 my $query = "SELECT * FROM saved_reports WHERE report_id=?";
600 my $sth = $dbh->prepare($query);
602 if (my $data=$sth->fetchrow_hashref()){
603 my $query2 = "UPDATE saved_reports SET report=?,date_run=now() WHERE report_id=?";
604 my $sth2 = $dbh->prepare($query2);
605 $sth2->execute($xml,$id);
608 my $query2 = "INSERT INTO saved_reports (report_id,report,date_run) VALUES (?,?,now())";
609 my $sth2 = $dbh->prepare($query2);
610 $sth2->execute($id,$xml);
616 my $dbh = C4::Context->dbh();
617 my $query = "SELECT * FROM saved_reports WHERE report_id = ?";
618 my $sth = $dbh->prepare($query);
620 my $data = $sth->fetchrow_hashref();
621 my $dump = new XML::Dumper;
622 my $perl = $dump->xml2pl( $data->{'report'} );
623 foreach my $row (@$perl) {
625 foreach my $key (keys %$row){
626 $htmlrow .= "<td>$row->{$key}</td>";
629 $row->{'row'} = $htmlrow;
632 $query = "SELECT * FROM saved_sql WHERE id = ?";
633 $sth = $dbh->prepare($query);
635 $data = $sth->fetchrow_hashref();
636 return ($perl,$data->{'report_name'},$data->{'notes'});
642 foreach my $id (@ids) {
643 my $data = get_saved_report($id);
644 logaction( "REPORTS", "DELETE", $id, "$data->{'report_name'} | $data->{'savedsql'} " ) if C4::Context->preference("ReportsLog");
646 my $dbh = C4::Context->dbh;
647 my $query = 'DELETE FROM saved_sql WHERE id IN (' . join( ',', ('?') x @ids ) . ')';
648 my $sth = $dbh->prepare($query);
649 return $sth->execute(@ids);
652 sub get_saved_reports_base_query {
653 my $area_name_sql_snippet = get_area_name_sql_snippet;
655 SELECT s.*, r.report, r.date_run, $area_name_sql_snippet, av_g.lib AS groupname, av_sg.lib AS subgroupname,
656 b.firstname AS borrowerfirstname, b.surname AS borrowersurname
658 LEFT JOIN saved_reports r ON r.report_id = s.id
659 LEFT OUTER JOIN authorised_values av_g ON (av_g.category = 'REPORT_GROUP' AND av_g.authorised_value = s.report_group)
660 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)
661 LEFT OUTER JOIN borrowers b USING (borrowernumber)
665 sub get_saved_reports {
666 # $filter is either { date => $d, author => $a, keyword => $kw, }
667 # or $keyword. Optional.
669 $filter = { keyword => $filter } if $filter && !ref( $filter );
670 my ($group, $subgroup) = @_;
672 my $dbh = C4::Context->dbh();
673 my $query = get_saved_reports_base_query;
676 if (my $date = $filter->{date}) {
677 $date = eval { output_pref( { dt => dt_from_string( $date ), dateonly => 1, dateformat => 'iso' }); };
678 push @cond, "DATE(date_run) = ? OR
679 DATE(date_created) = ? OR
680 DATE(last_modified) = ? OR
682 push @args, $date, $date, $date, $date;
684 if (my $author = $filter->{author}) {
685 $author = "%$author%";
686 push @cond, "surname LIKE ? OR
688 push @args, $author, $author;
690 if (my $keyword = $filter->{keyword}) {
693 OR report_name LIKE ?
698 push @args, "%$keyword%", "%$keyword%", "%$keyword%", "%$keyword%", $keyword;
700 if ($filter->{group}) {
701 push @cond, "report_group = ?";
702 push @args, $filter->{group};
704 if ($filter->{subgroup}) {
705 push @cond, "report_subgroup = ?";
706 push @args, $filter->{subgroup};
709 $query .= " WHERE ".join( " AND ", map "($_)", @cond ) if @cond;
710 $query .= " ORDER by date_created";
712 my $result = $dbh->selectall_arrayref($query, {Slice => {}}, @args);
717 sub get_saved_report {
718 my $dbh = C4::Context->dbh();
721 if ($#_ == 0 && ref $_[0] ne 'HASH') {
723 $query = " SELECT * FROM saved_sql WHERE id = ?";
724 } elsif (ref $_[0] eq 'HASH') {
726 if ($selector->{name}) {
727 $query = " SELECT * FROM saved_sql WHERE report_name = ?";
728 $report_arg = $selector->{name};
729 } elsif ($selector->{id} || $selector->{id} eq '0') {
730 $query = " SELECT * FROM saved_sql WHERE id = ?";
731 $report_arg = $selector->{id};
738 return $dbh->selectrow_hashref($query, undef, $report_arg);
741 =head2 create_compound($masterID,$subreportID)
743 This will take 2 reports and create a compound report using both of them
747 sub create_compound {
748 my ( $masterID, $subreportID ) = @_;
749 my $dbh = C4::Context->dbh();
752 my $master = get_saved_report($masterID);
753 my $mastersql = $master->{savedsql};
754 my $mastertype = $master->{type};
755 my $sub = get_saved_report($subreportID);
756 my $subsql = $master->{savedsql};
757 my $subtype = $master->{type};
759 # now we have to do some checking to see how these two will fit together
761 my ( $mastertables, $subtables );
762 if ( $mastersql =~ / from (.*) where /i ) {
765 if ( $subsql =~ / from (.*) where /i ) {
768 return ( $mastertables, $subtables );
771 =head2 get_column_type($column)
773 This takes a column name of the format table.column and will return what type it is
774 (free text, set values, date)
778 sub get_column_type {
779 my ($tablecolumn) = @_;
780 my ($table,$column) = split(/\./,$tablecolumn);
781 my $dbh = C4::Context->dbh();
785 # mysql doesn't support a column selection, set column to %
787 my $sth = $dbh->column_info( $catalog, $schema, $table, $tempcolumn ) || die $dbh->errstr;
788 while (my $info = $sth->fetchrow_hashref()){
789 if ($info->{'COLUMN_NAME'} eq $column){
791 if ($info->{'TYPE_NAME'} eq 'CHAR' || $info->{'TYPE_NAME'} eq 'VARCHAR'){
792 $info->{'TYPE_NAME'} = 'distinct';
794 return $info->{'TYPE_NAME'};
799 =head2 get_distinct_values($column)
801 Given a column name, return an arrary ref of hashrefs suitable for use as a tmpl_loop
802 with the distinct values of the column
806 sub get_distinct_values {
807 my ($tablecolumn) = @_;
808 my ($table,$column) = split(/\./,$tablecolumn);
809 my $dbh = C4::Context->dbh();
811 "SELECT distinct($column) as availablevalues FROM $table";
812 my $sth = $dbh->prepare($query);
814 return $sth->fetchall_arrayref({});
817 sub save_dictionary {
818 my ( $name, $description, $sql, $area ) = @_;
819 my $dbh = C4::Context->dbh();
820 my $query = "INSERT INTO reports_dictionary (name,description,saved_sql,report_area,date_created,date_modified)
821 VALUES (?,?,?,?,now(),now())";
822 my $sth = $dbh->prepare($query);
823 $sth->execute($name,$description,$sql,$area) || return 0;
827 sub get_from_dictionary {
828 my ( $area, $id ) = @_;
829 my $dbh = C4::Context->dbh();
830 my $area_name_sql_snippet = get_area_name_sql_snippet;
832 SELECT d.*, $area_name_sql_snippet
833 FROM reports_dictionary d
837 $query .= " WHERE report_area = ?";
839 $query .= " WHERE id = ?";
841 my $sth = $dbh->prepare($query);
845 $sth->execute($area);
850 while ( my $data = $sth->fetchrow_hashref() ) {
856 sub delete_definition {
857 my ($id) = @_ or return;
858 my $dbh = C4::Context->dbh();
859 my $query = "DELETE FROM reports_dictionary WHERE id = ?";
860 my $sth = $dbh->prepare($query);
865 my ($id) = @_ or return;
866 my $dbh = C4::Context->dbh();
867 my $query = "SELECT * FROM saved_sql WHERE id = ?";
868 my $sth = $dbh->prepare($query);
870 my $data=$sth->fetchrow_hashref();
871 return $data->{'savedsql'};
874 sub _get_column_defs {
877 my $columns_def_file = "columns.def";
878 my $htdocs = C4::Context->config('intrahtdocs');
879 my $section = 'intranet';
881 # We need the theme and the lang
882 # Since columns.def is not in the modules directory, we cannot sent it for the $tmpl var
883 my ($theme, $lang, $availablethemes) = C4::Templates::themelanguage($htdocs, 'about.tt', $section, $cgi);
885 my $full_path_to_columns_def_file="$htdocs/$theme/$lang/$columns_def_file";
886 open (my $fh, '<:encoding(utf-8)', $full_path_to_columns_def_file);
887 while ( my $input = <$fh> ){
889 if ( $input =~ m|<field name="(.*)">(.*)</field>| ) {
890 my ( $field, $translation ) = ( $1, $2 );
891 $columns{$field} = $translation;
898 =head2 GetReservedAuthorisedValues
900 my %reserved_authorised_values = GetReservedAuthorisedValues();
902 Returns a hash containig all reserved words
906 sub GetReservedAuthorisedValues {
907 my %reserved_authorised_values =
908 map { $_ => 1 } ( 'date',
913 'biblio_framework' );
915 return \%reserved_authorised_values;
919 =head2 IsAuthorisedValueValid
921 my $is_valid_ath_value = IsAuthorisedValueValid($authorised_value)
923 Returns 1 if $authorised_value is on the reserved authorised values list or
924 in the authorised value categories defined in
928 sub IsAuthorisedValueValid {
930 my $authorised_value = shift;
931 my $reserved_authorised_values = GetReservedAuthorisedValues();
933 if ( exists $reserved_authorised_values->{$authorised_value} ||
934 Koha::AuthorisedValues->search({ category => $authorised_value })->count ) {
941 =head2 GetParametersFromSQL
943 my @sql_parameters = GetParametersFromSQL($sql)
945 Returns an arrayref of hashes containing the keys name and authval
949 sub GetParametersFromSQL {
952 my @split = split(/<<|>>/,$sql);
953 my @sql_parameters = ();
955 for ( my $i = 0; $i < ($#split/2) ; $i++ ) {
956 my ($name,$authval) = split(/\|/,$split[$i*2+1]);
957 push @sql_parameters, { 'name' => $name, 'authval' => $authval };
960 return \@sql_parameters;
963 =head2 ValidateSQLParameters
965 my @problematic_parameters = ValidateSQLParameters($sql)
967 Returns an arrayref of hashes containing the keys name and authval of
968 those SQL parameters that do not correspond to valid authorised names
972 sub ValidateSQLParameters {
975 my @problematic_parameters = ();
976 my $sql_parameters = GetParametersFromSQL($sql);
978 foreach my $sql_parameter (@$sql_parameters) {
979 if ( defined $sql_parameter->{'authval'} ) {
980 push @problematic_parameters, $sql_parameter unless
981 IsAuthorisedValueValid($sql_parameter->{'authval'});
985 return \@problematic_parameters;
988 sub _get_display_value {
989 my ( $original_value, $column ) = @_;
990 if ( $column eq 'periodicity' ) {
991 my $dbh = C4::Context->dbh();
992 my $query = "SELECT description FROM subscription_frequencies WHERE id = ?";
993 my $sth = $dbh->prepare($query);
994 $sth->execute($original_value);
995 return $sth->fetchrow;
997 return $original_value;
1005 Chris Cormack <crc@liblime.com>