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($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
26 use C4::Templates qw/themelanguage/;
33 # use Smart::Comments;
37 use Koha::AuthorisedValues;
40 # set the version for version checking
41 $VERSION = 3.07.00.049;
45 get_report_types get_report_areas get_report_groups get_columns build_query get_criteria
46 save_report get_saved_reports execute_query get_saved_report create_compound run_compound
47 get_column_type get_distinct_values save_dictionary get_from_dictionary
48 delete_definition delete_report format_results get_sql
50 GetReservedAuthorisedValues
52 IsAuthorisedValueValid
60 C4::Reports::Guided - Module for generating guided reports
64 use C4::Reports::Guided;
72 =head2 get_report_areas
74 This will return a list of all the available report areas
78 sub get_area_name_sql_snippet {
80 [CIRC => "Circulation"],
83 [ACQ => "Acquisition"],
88 return "CASE report_area " .
89 join (" ", map "WHEN '$_->[0]' THEN '$_->[1]'", @REPORT_AREA) .
93 sub get_report_areas {
95 my $report_areas = [ 'CIRC', 'CAT', 'PAT', 'ACQ', 'ACC', 'SER' ];
100 sub get_table_areas {
102 CIRC => [ 'borrowers', 'statistics', 'items', 'biblioitems' ],
103 CAT => [ 'items', 'biblioitems', 'biblio' ],
104 PAT => ['borrowers'],
105 ACQ => [ 'aqorders', 'biblio', 'items' ],
106 ACC => [ 'borrowers', 'accountlines' ],
107 SER => [ 'serial', 'serialitems', 'subscription', 'subscriptionhistory', 'subscriptionroutinglist', 'biblioitems', 'biblio', 'aqbooksellers' ],
111 =head2 get_report_types
113 This will return a list of all the available report types
117 sub get_report_types {
118 my $dbh = C4::Context->dbh();
120 # FIXME these should be in the database perhaps
121 my @reports = ( 'Tabular', 'Summary', 'Matrix' );
123 for ( my $i = 0 ; $i < 3 ; $i++ ) {
125 $hashrep{id} = $i + 1;
126 $hashrep{name} = $reports[$i];
127 push @reports2, \%hashrep;
129 return ( \@reports2 );
133 =head2 get_report_groups
135 This will return a list of all the available report areas with groups
139 sub get_report_groups {
140 my $dbh = C4::Context->dbh();
142 my $groups = GetAuthorisedValues('REPORT_GROUP');
143 my $subgroups = GetAuthorisedValues('REPORT_SUBGROUP');
145 my %groups_with_subgroups = map { $_->{authorised_value} => {
149 foreach (@$subgroups) {
150 my $sg = $_->{authorised_value};
151 my $g = $_->{lib_opac}
152 or warn( qq{REPORT_SUBGROUP "$sg" without REPORT_GROUP (lib_opac)} ),
154 my $g_sg = $groups_with_subgroups{$g}
155 or warn( qq{REPORT_SUBGROUP "$sg" with invalid REPORT_GROUP "$g"} ),
157 $g_sg->{subgroups}{$sg} = $_->{lib};
159 return \%groups_with_subgroups
162 =head2 get_all_tables
164 This will return a list of all tables in the database
169 my $dbh = C4::Context->dbh();
170 my $query = "SHOW TABLES";
171 my $sth = $dbh->prepare($query);
174 while ( my $data = $sth->fetchrow_arrayref() ) {
175 push @tables, $data->[0];
182 =head2 get_columns($area)
184 This will return a list of all columns for a report area
190 # this calls the internal function _get_columns
191 my ( $area, $cgi ) = @_;
192 my %table_areas = get_table_areas;
193 my $tables = $table_areas{$area}
194 or die qq{Unsuported report area "$area"};
198 foreach my $table (@$tables) {
199 my @columns = _get_columns($table,$cgi, $first);
201 push @allcolumns, @columns;
203 return ( \@allcolumns );
207 my ($tablename,$cgi, $first) = @_;
208 my $dbh = C4::Context->dbh();
209 my $sth = $dbh->prepare("show columns from $tablename");
212 my $column_defs = _get_column_defs($cgi);
214 $tablehash{'table'}=$tablename;
215 $tablehash{'__first__'} = $first;
216 push @columns, \%tablehash;
217 while ( my $data = $sth->fetchrow_arrayref() ) {
219 $temphash{'name'} = "$tablename.$data->[0]";
220 $temphash{'description'} = $column_defs->{"$tablename.$data->[0]"};
221 push @columns, \%temphash;
227 =head2 build_query($columns,$criteria,$orderby,$area)
229 This will build the sql needed to return the results asked for,
230 $columns is expected to be of the format tablename.columnname.
231 This is what get_columns returns.
236 my ( $columns, $criteria, $orderby, $area, $totals, $definition ) = @_;
239 CIRC => [ 'statistics.borrowernumber=borrowers.borrowernumber',
240 'items.itemnumber = statistics.itemnumber',
241 'biblioitems.biblioitemnumber = items.biblioitemnumber' ],
242 CAT => [ 'items.biblioitemnumber=biblioitems.biblioitemnumber',
243 'biblioitems.biblionumber=biblio.biblionumber' ],
245 ACQ => [ 'aqorders.biblionumber=biblio.biblionumber',
246 'biblio.biblionumber=items.biblionumber' ],
247 ACC => ['borrowers.borrowernumber=accountlines.borrowernumber'],
248 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'],
253 my $keys = $keys{$area};
254 my %table_areas = get_table_areas;
255 my $tables = $table_areas{$area};
258 _build_query( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition );
263 my ( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition) = @_;
265 # $keys is an array of joining constraints
266 my $dbh = C4::Context->dbh();
267 my $joinedtables = join( ',', @$tables );
268 my $joinedcolumns = join( ',', @$columns );
270 "SELECT $totals $joinedcolumns FROM $tables->[0] ";
271 for (my $i=1;$i<@$tables;$i++){
272 $query .= "LEFT JOIN $tables->[$i] on ($keys->[$i-1]) ";
276 $criteria =~ s/AND/WHERE/;
277 $query .= " $criteria";
280 my @definitions = split(',',$definition);
282 foreach my $def (@definitions){
283 my $defin=get_from_dictionary('',$def);
284 $deftext .=" ".$defin->[0]->{'saved_sql'};
286 if ($query =~ /WHERE/i){
290 $deftext =~ s/AND/WHERE/;
296 my @totcolumns = split( ',', $totals );
297 foreach my $total (@totcolumns) {
298 if ( $total =~ /\((.*)\)/ ) {
299 if ( $groupby eq '' ) {
300 $groupby = " GROUP BY $1";
315 =head2 get_criteria($area,$cgi);
317 Returns an arraref to hashrefs suitable for using in a tmpl_loop. With the criteria and available values.
322 my ($area,$cgi) = @_;
323 my $dbh = C4::Context->dbh();
325 # have to do someting here to know if its dropdown, free text, date etc
327 CIRC => [ 'statistics.type', 'borrowers.categorycode', 'statistics.branch',
328 'biblioitems.publicationyear|date', 'items.dateaccessioned|date' ],
329 CAT => [ 'items.itemnumber|textrange', 'items.biblionumber|textrange',
330 'items.barcode|textrange', 'biblio.frameworkcode',
331 'items.holdingbranch', 'items.homebranch',
332 'biblio.datecreated|daterange', 'biblio.timestamp|daterange',
333 'items.onloan|daterange', 'items.ccode',
334 'items.itemcallnumber|textrange', 'items.itype', 'items.itemlost',
336 PAT => [ 'borrowers.branchcode', 'borrowers.categorycode' ],
337 ACQ => ['aqorders.datereceived|date'],
338 ACC => [ 'borrowers.branchcode', 'borrowers.categorycode' ],
339 SER => ['subscription.startdate|date', 'subscription.enddate|date', 'subscription.periodicity', 'subscription.callnumber', 'subscription.location', 'subscription.branchcode'],
342 # Adds itemtypes to criteria, according to the syspref
343 if ( C4::Context->preference('item-level_itypes') ) {
344 unshift @{ $criteria{'CIRC'} }, 'items.itype';
345 unshift @{ $criteria{'CAT'} }, 'items.itype';
347 unshift @{ $criteria{'CIRC'} }, 'biblioitems.itemtype';
348 unshift @{ $criteria{'CAT'} }, 'biblioitems.itemtype';
352 my $crit = $criteria{$area};
353 my $column_defs = _get_column_defs($cgi);
355 foreach my $localcrit (@$crit) {
356 my ( $value, $type ) = split( /\|/, $localcrit );
357 my ( $table, $column ) = split( /\./, $value );
358 if ($type eq 'textrange') {
360 $temp{'name'} = $value;
361 $temp{'from'} = "from_" . $value;
362 $temp{'to'} = "to_" . $value;
363 $temp{'textrange'} = 1;
364 $temp{'description'} = $column_defs->{$value};
365 push @criteria_array, \%temp;
367 elsif ($type eq 'date') {
369 $temp{'name'} = $value;
371 $temp{'description'} = $column_defs->{$value};
372 push @criteria_array, \%temp;
374 elsif ($type eq 'daterange') {
376 $temp{'name'} = $value;
377 $temp{'from'} = "from_" . $value;
378 $temp{'to'} = "to_" . $value;
379 $temp{'daterange'} = 1;
380 $temp{'description'} = $column_defs->{$value};
381 push @criteria_array, \%temp;
385 "SELECT distinct($column) as availablevalues FROM $table";
386 my $sth = $dbh->prepare($query);
389 # push the runtime choosing option
391 $list='branches' if $column eq 'branchcode' or $column eq 'holdingbranch' or $column eq 'homebranch';
392 $list='categorycode' if $column eq 'categorycode';
393 $list='itemtypes' if $column eq 'itype';
394 $list='ccode' if $column eq 'ccode';
395 # TODO : improve to let the librarian choose the description at runtime
397 availablevalues => "<<$column" . ( $list ? "|$list" : '' ) . ">>",
398 display_value => "<<$column" . ( $list ? "|$list" : '' ) . ">>",
400 while ( my $row = $sth->fetchrow_hashref() ) {
401 if ($row->{'availablevalues'} eq '') { $row->{'default'} = 1 }
402 else { $row->{display_value} = _get_display_value( $row->{'availablevalues'}, $column ); }
408 $temp{'name'} = $value;
409 $temp{'description'} = $column_defs->{$value};
410 $temp{'values'} = \@values;
412 push @criteria_array, \%temp;
415 return ( \@criteria_array );
419 my $sql = shift or return;
420 my $sth = C4::Context->dbh->prepare($sql);
422 my $rows = $sth->fetchall_arrayref();
423 return scalar (@$rows);
428 ($sth, $error) = execute_query($sql, $offset, $limit[, \@sql_params])
431 This function returns a DBI statement handler from which the caller can
432 fetch the results of the SQL passed via C<$sql>.
434 If passed any query other than a SELECT, or if there is a DB error,
435 C<$errors> is returned, and is a hashref containing the error after this
438 C<$error->{'sqlerr'}> contains the offending SQL keyword.
439 C<$error->{'queryerr'}> contains the native db engine error returned
442 C<$offset>, and C<$limit> are required parameters.
444 C<\@sql_params> is an optional list of parameter values to paste in.
445 The caller is responsible for making sure that C<$sql> has placeholders
446 and that the number placeholders matches the number of parameters.
450 # returns $sql, $offset, $limit
451 # $sql returned will be transformed to:
452 # ~ remove any LIMIT clause
453 # ~ repace SELECT clause w/ SELECT count(*)
455 sub select_2_select_count {
456 # Modify the query passed in to create a count query... (I think this covers all cases -crn)
457 my ($sql) = strip_limit(shift) or return;
458 $sql =~ s/\bSELECT\W+(?:\w+\W+){1,}?FROM\b|\bSELECT\W\*\WFROM\b/SELECT count(*) FROM /ig;
462 # This removes the LIMIT from the query so that a custom one can be specified.
464 # ($new_sql, $offset, $limit) = strip_limit($sql);
467 # $sql is the query to modify
468 # $new_sql is the resulting query
469 # $offset is the offset value, if the LIMIT was the two-argument form,
470 # 0 if it wasn't otherwise given.
471 # $limit is the limit value
474 # * This makes an effort to not break subqueries that have their own
475 # LIMIT specified. It does that by only removing a LIMIT if it comes after
476 # a WHERE clause (which isn't perfect, but at least should make more cases
477 # work - subqueries with a limit in the WHERE will still break.)
478 # * If your query doesn't have a WHERE clause then all LIMITs will be
479 # removed. This may break some subqueries, but is hopefully rare enough
480 # to not be a big issue.
485 return ($sql, 0, undef) unless $sql =~ /\bLIMIT\b/i;
487 # Two options: if there's no WHERE clause in the SQL, we simply capture
488 # any LIMIT that's there. If there is a WHERE, we make sure that we only
489 # capture a LIMIT after the last one. This prevents stomping on subqueries.
490 if ($sql !~ /\bWHERE\b/i) {
491 (my $res = $sql) =~ s/\bLIMIT\b\s*(\d+)(\s*\,\s*(\d+))?\s*/ /ig;
492 return ($res, (defined $2 ? $1 : 0), (defined $3 ? $3 : $1));
495 $res =~ m/.*\bWHERE\b/gsi;
496 $res =~ s/\G(.*)\bLIMIT\b\s*(\d+)(\s*\,\s*(\d+))?\s*/$1 /is;
497 return ($res, (defined $3 ? $2 : 0), (defined $4 ? $4 : $2));
503 my ( $sql, $offset, $limit, $sql_params ) = @_;
505 $sql_params = [] unless defined $sql_params;
509 carp "execute_query() called without SQL argument";
512 $offset = 0 unless $offset;
513 $limit = 999999 unless $limit;
514 $debug and print STDERR "execute_query($sql, $offset, $limit)\n";
515 if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
516 return (undef, { sqlerr => $1} );
517 } elsif ($sql !~ /^\s*SELECT\b\s*/i) {
518 return (undef, { queryerr => 'Missing SELECT'} );
521 my ($useroffset, $userlimit);
523 # Grab offset/limit from user supplied LIMIT and drop the LIMIT so we can control pagination
524 ($sql, $useroffset, $userlimit) = strip_limit($sql);
525 $debug and warn sprintf "User has supplied (OFFSET,) LIMIT = %s, %s",
527 (defined($userlimit ) ? $userlimit : 'UNDEF');
528 $offset += $useroffset;
529 if (defined($userlimit)) {
530 if ($offset + $limit > $userlimit ) {
531 $limit = $userlimit - $offset;
532 } elsif ( ! $offset && $limit < $userlimit ) {
536 $sql .= " LIMIT ?, ?";
538 my $sth = C4::Context->dbh->prepare($sql);
539 $sth->execute(@$sql_params, $offset, $limit);
540 return ( $sth, { queryerr => $sth->errstr } ) if ($sth->err);
542 # my @xmlarray = ... ;
543 # my $url = "/cgi-bin/koha/reports/guided_reports.pl?phase=retrieve%20results&id=$id";
544 # my $xml = XML::Dumper->new()->pl2xml( \@xmlarray );
545 # store_results($id,$xml);
548 =head2 save_report($sql,$name,$type,$notes)
550 Given some sql and a name this will saved it so that it can reused
551 Returns id of the newly created report
557 my $borrowernumber = $fields->{borrowernumber};
558 my $sql = $fields->{sql};
559 my $name = $fields->{name};
560 my $type = $fields->{type};
561 my $notes = $fields->{notes};
562 my $area = $fields->{area};
563 my $group = $fields->{group};
564 my $subgroup = $fields->{subgroup};
565 my $cache_expiry = $fields->{cache_expiry} || 300;
566 my $public = $fields->{public};
568 my $dbh = C4::Context->dbh();
569 $sql =~ s/(\s*\;\s*)$//; # removes trailing whitespace and /;/
570 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(),?,?,?,?,?,?,?,?,?)";
571 $dbh->do($query, undef, $borrowernumber, $sql, $name, $area, $group, $subgroup, $type, $notes, $cache_expiry, $public);
573 my $id = $dbh->selectrow_array("SELECT max(id) FROM saved_sql WHERE borrowernumber=? AND report_name=?", undef,
574 $borrowernumber, $name);
579 my $id = shift || croak "No Id given";
581 my $sql = $fields->{sql};
582 my $name = $fields->{name};
583 my $notes = $fields->{notes};
584 my $group = $fields->{group};
585 my $subgroup = $fields->{subgroup};
586 my $cache_expiry = $fields->{cache_expiry};
587 my $public = $fields->{public};
589 if( $cache_expiry >= 2592000 ){
590 die "Please specify a cache expiry less than 30 days\n";
593 my $dbh = C4::Context->dbh();
594 $sql =~ s/(\s*\;\s*)$//; # removes trailing whitespace and /;/
595 my $query = "UPDATE saved_sql SET savedsql = ?, last_modified = now(), report_name = ?, report_group = ?, report_subgroup = ?, notes = ?, cache_expiry = ?, public = ? WHERE id = ? ";
596 $dbh->do($query, undef, $sql, $name, $group, $subgroup, $notes, $cache_expiry, $public, $id );
601 my $dbh = C4::Context->dbh();
602 my $query = "SELECT * FROM saved_reports WHERE report_id=?";
603 my $sth = $dbh->prepare($query);
605 if (my $data=$sth->fetchrow_hashref()){
606 my $query2 = "UPDATE saved_reports SET report=?,date_run=now() WHERE report_id=?";
607 my $sth2 = $dbh->prepare($query2);
608 $sth2->execute($xml,$id);
611 my $query2 = "INSERT INTO saved_reports (report_id,report,date_run) VALUES (?,?,now())";
612 my $sth2 = $dbh->prepare($query2);
613 $sth2->execute($id,$xml);
619 my $dbh = C4::Context->dbh();
620 my $query = "SELECT * FROM saved_reports WHERE report_id = ?";
621 my $sth = $dbh->prepare($query);
623 my $data = $sth->fetchrow_hashref();
624 my $dump = new XML::Dumper;
625 my $perl = $dump->xml2pl( $data->{'report'} );
626 foreach my $row (@$perl) {
628 foreach my $key (keys %$row){
629 $htmlrow .= "<td>$row->{$key}</td>";
632 $row->{'row'} = $htmlrow;
635 $query = "SELECT * FROM saved_sql WHERE id = ?";
636 $sth = $dbh->prepare($query);
638 $data = $sth->fetchrow_hashref();
639 return ($perl,$data->{'report_name'},$data->{'notes'});
645 foreach my $id (@ids) {
646 my $data = get_saved_report($id);
647 logaction( "REPORTS", "DELETE", $id, "$data->{'report_name'} | $data->{'savedsql'} " ) if C4::Context->preference("ReportsLog");
649 my $dbh = C4::Context->dbh;
650 my $query = 'DELETE FROM saved_sql WHERE id IN (' . join( ',', ('?') x @ids ) . ')';
651 my $sth = $dbh->prepare($query);
652 return $sth->execute(@ids);
655 sub get_saved_reports_base_query {
656 my $area_name_sql_snippet = get_area_name_sql_snippet;
658 SELECT s.*, r.report, r.date_run, $area_name_sql_snippet, av_g.lib AS groupname, av_sg.lib AS subgroupname,
659 b.firstname AS borrowerfirstname, b.surname AS borrowersurname
661 LEFT JOIN saved_reports r ON r.report_id = s.id
662 LEFT OUTER JOIN authorised_values av_g ON (av_g.category = 'REPORT_GROUP' AND av_g.authorised_value = s.report_group)
663 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)
664 LEFT OUTER JOIN borrowers b USING (borrowernumber)
668 sub get_saved_reports {
669 # $filter is either { date => $d, author => $a, keyword => $kw, }
670 # or $keyword. Optional.
672 $filter = { keyword => $filter } if $filter && !ref( $filter );
673 my ($group, $subgroup) = @_;
675 my $dbh = C4::Context->dbh();
676 my $query = get_saved_reports_base_query;
679 if (my $date = $filter->{date}) {
680 $date = eval { output_pref( { dt => dt_from_string( $date ), dateonly => 1, dateformat => 'iso' }); };
681 push @cond, "DATE(date_run) = ? OR
682 DATE(date_created) = ? OR
683 DATE(last_modified) = ? OR
685 push @args, $date, $date, $date, $date;
687 if (my $author = $filter->{author}) {
688 $author = "%$author%";
689 push @cond, "surname LIKE ? OR
691 push @args, $author, $author;
693 if (my $keyword = $filter->{keyword}) {
696 OR report_name LIKE ?
701 push @args, "%$keyword%", "%$keyword%", "%$keyword%", "%$keyword%", $keyword;
703 if ($filter->{group}) {
704 push @cond, "report_group = ?";
705 push @args, $filter->{group};
707 if ($filter->{subgroup}) {
708 push @cond, "report_subgroup = ?";
709 push @args, $filter->{subgroup};
712 $query .= " WHERE ".join( " AND ", map "($_)", @cond ) if @cond;
713 $query .= " ORDER by date_created";
715 my $result = $dbh->selectall_arrayref($query, {Slice => {}}, @args);
720 sub get_saved_report {
721 my $dbh = C4::Context->dbh();
724 if ($#_ == 0 && ref $_[0] ne 'HASH') {
726 $query = " SELECT * FROM saved_sql WHERE id = ?";
727 } elsif (ref $_[0] eq 'HASH') {
729 if ($selector->{name}) {
730 $query = " SELECT * FROM saved_sql WHERE report_name = ?";
731 $report_arg = $selector->{name};
732 } elsif ($selector->{id} || $selector->{id} eq '0') {
733 $query = " SELECT * FROM saved_sql WHERE id = ?";
734 $report_arg = $selector->{id};
741 return $dbh->selectrow_hashref($query, undef, $report_arg);
744 =head2 create_compound($masterID,$subreportID)
746 This will take 2 reports and create a compound report using both of them
750 sub create_compound {
751 my ( $masterID, $subreportID ) = @_;
752 my $dbh = C4::Context->dbh();
755 my $master = get_saved_report($masterID);
756 my $mastersql = $master->{savedsql};
757 my $mastertype = $master->{type};
758 my $sub = get_saved_report($subreportID);
759 my $subsql = $master->{savedsql};
760 my $subtype = $master->{type};
762 # now we have to do some checking to see how these two will fit together
764 my ( $mastertables, $subtables );
765 if ( $mastersql =~ / from (.*) where /i ) {
768 if ( $subsql =~ / from (.*) where /i ) {
771 return ( $mastertables, $subtables );
774 =head2 get_column_type($column)
776 This takes a column name of the format table.column and will return what type it is
777 (free text, set values, date)
781 sub get_column_type {
782 my ($tablecolumn) = @_;
783 my ($table,$column) = split(/\./,$tablecolumn);
784 my $dbh = C4::Context->dbh();
788 # mysql doesn't support a column selection, set column to %
790 my $sth = $dbh->column_info( $catalog, $schema, $table, $tempcolumn ) || die $dbh->errstr;
791 while (my $info = $sth->fetchrow_hashref()){
792 if ($info->{'COLUMN_NAME'} eq $column){
794 if ($info->{'TYPE_NAME'} eq 'CHAR' || $info->{'TYPE_NAME'} eq 'VARCHAR'){
795 $info->{'TYPE_NAME'} = 'distinct';
797 return $info->{'TYPE_NAME'};
802 =head2 get_distinct_values($column)
804 Given a column name, return an arrary ref of hashrefs suitable for use as a tmpl_loop
805 with the distinct values of the column
809 sub get_distinct_values {
810 my ($tablecolumn) = @_;
811 my ($table,$column) = split(/\./,$tablecolumn);
812 my $dbh = C4::Context->dbh();
814 "SELECT distinct($column) as availablevalues FROM $table";
815 my $sth = $dbh->prepare($query);
817 return $sth->fetchall_arrayref({});
820 sub save_dictionary {
821 my ( $name, $description, $sql, $area ) = @_;
822 my $dbh = C4::Context->dbh();
823 my $query = "INSERT INTO reports_dictionary (name,description,saved_sql,report_area,date_created,date_modified)
824 VALUES (?,?,?,?,now(),now())";
825 my $sth = $dbh->prepare($query);
826 $sth->execute($name,$description,$sql,$area) || return 0;
830 sub get_from_dictionary {
831 my ( $area, $id ) = @_;
832 my $dbh = C4::Context->dbh();
833 my $area_name_sql_snippet = get_area_name_sql_snippet;
835 SELECT d.*, $area_name_sql_snippet
836 FROM reports_dictionary d
840 $query .= " WHERE report_area = ?";
842 $query .= " WHERE id = ?";
844 my $sth = $dbh->prepare($query);
848 $sth->execute($area);
853 while ( my $data = $sth->fetchrow_hashref() ) {
859 sub delete_definition {
860 my ($id) = @_ or return;
861 my $dbh = C4::Context->dbh();
862 my $query = "DELETE FROM reports_dictionary WHERE id = ?";
863 my $sth = $dbh->prepare($query);
868 my ($id) = @_ or return;
869 my $dbh = C4::Context->dbh();
870 my $query = "SELECT * FROM saved_sql WHERE id = ?";
871 my $sth = $dbh->prepare($query);
873 my $data=$sth->fetchrow_hashref();
874 return $data->{'savedsql'};
877 sub _get_column_defs {
880 my $columns_def_file = "columns.def";
881 my $htdocs = C4::Context->config('intrahtdocs');
882 my $section = 'intranet';
884 # We need the theme and the lang
885 # Since columns.def is not in the modules directory, we cannot sent it for the $tmpl var
886 my ($theme, $lang, $availablethemes) = C4::Templates::themelanguage($htdocs, 'about.tt', $section, $cgi);
888 my $full_path_to_columns_def_file="$htdocs/$theme/$lang/$columns_def_file";
889 open (my $fh, '<:encoding(utf-8)', $full_path_to_columns_def_file);
890 while ( my $input = <$fh> ){
892 if ( $input =~ m|<field name="(.*)">(.*)</field>| ) {
893 my ( $field, $translation ) = ( $1, $2 );
894 $columns{$field} = $translation;
901 =head2 GetReservedAuthorisedValues
903 my %reserved_authorised_values = GetReservedAuthorisedValues();
905 Returns a hash containig all reserved words
909 sub GetReservedAuthorisedValues {
910 my %reserved_authorised_values =
911 map { $_ => 1 } ( 'date',
916 'biblio_framework' );
918 return \%reserved_authorised_values;
922 =head2 IsAuthorisedValueValid
924 my $is_valid_ath_value = IsAuthorisedValueValid($authorised_value)
926 Returns 1 if $authorised_value is on the reserved authorised values list or
927 in the authorised value categories defined in
931 sub IsAuthorisedValueValid {
933 my $authorised_value = shift;
934 my $reserved_authorised_values = GetReservedAuthorisedValues();
936 if ( exists $reserved_authorised_values->{$authorised_value} ||
937 Koha::AuthorisedValues->search({ category => $authorised_value })->count ) {
944 =head2 GetParametersFromSQL
946 my @sql_parameters = GetParametersFromSQL($sql)
948 Returns an arrayref of hashes containing the keys name and authval
952 sub GetParametersFromSQL {
955 my @split = split(/<<|>>/,$sql);
956 my @sql_parameters = ();
958 for ( my $i = 0; $i < ($#split/2) ; $i++ ) {
959 my ($name,$authval) = split(/\|/,$split[$i*2+1]);
960 push @sql_parameters, { 'name' => $name, 'authval' => $authval };
963 return \@sql_parameters;
966 =head2 ValidateSQLParameters
968 my @problematic_parameters = ValidateSQLParameters($sql)
970 Returns an arrayref of hashes containing the keys name and authval of
971 those SQL parameters that do not correspond to valid authorised names
975 sub ValidateSQLParameters {
978 my @problematic_parameters = ();
979 my $sql_parameters = GetParametersFromSQL($sql);
981 foreach my $sql_parameter (@$sql_parameters) {
982 if ( defined $sql_parameter->{'authval'} ) {
983 push @problematic_parameters, $sql_parameter unless
984 IsAuthorisedValueValid($sql_parameter->{'authval'});
988 return \@problematic_parameters;
991 sub _get_display_value {
992 my ( $original_value, $column ) = @_;
993 if ( $column eq 'periodicity' ) {
994 my $dbh = C4::Context->dbh();
995 my $query = "SELECT description FROM subscription_frequencies WHERE id = ?";
996 my $sth = $dbh->prepare($query);
997 $sth->execute($original_value);
998 return $sth->fetchrow;
1000 return $original_value;
1008 Chris Cormack <crc@liblime.com>