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
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.
21 #use warnings; FIXME - Bug 2505 this module needs a lot of repair to run clean under warnings
25 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
27 use C4::Dates qw/format_date format_date_in_iso/;
28 use C4::Templates qw/themelanguage/;
34 # use Smart::Comments;
38 # set the version for version checking
39 $VERSION = 3.07.00.049;
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
50 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
76 [CIRC => "Circulation"],
79 [ACQ => "Acquisition"],
82 my $AREA_NAME_SQL_SNIPPET
83 = "CASE report_area " .
84 join (" ", map "WHEN '$_->[0]' THEN '$_->[1]'", @REPORT_AREA) .
86 sub get_report_areas {
91 CIRC => [ 'borrowers', 'statistics', 'items', 'biblioitems' ],
92 CAT => [ 'items', 'biblioitems', 'biblio' ],
94 ACQ => [ 'aqorders', 'biblio', 'items' ],
95 ACC => [ 'borrowers', 'accountlines' ],
98 CIRC => [ 'statistics.borrowernumber=borrowers.borrowernumber',
99 'items.itemnumber = statistics.itemnumber',
100 'biblioitems.biblioitemnumber = items.biblioitemnumber' ],
101 CAT => [ 'items.biblioitemnumber=biblioitems.biblioitemnumber',
102 'biblioitems.biblionumber=biblio.biblionumber' ],
104 ACQ => [ 'aqorders.biblionumber=biblio.biblionumber',
105 'biblio.biblionumber=items.biblionumber' ],
106 ACC => ['borrowers.borrowernumber=accountlines.borrowernumber'],
109 # have to do someting here to know if its dropdown, free text, date etc
111 CIRC => [ 'statistics.type', 'borrowers.categorycode', 'statistics.branch',
112 'biblioitems.publicationyear|date', 'items.dateaccessioned|date' ],
113 CAT => [ 'items.itemnumber|textrange', 'items.biblionumber|textrange',
114 'items.barcode|textrange', 'biblio.frameworkcode',
115 'items.holdingbranch', 'items.homebranch',
116 'biblio.datecreated|daterange', 'biblio.timestamp|daterange',
117 'items.onloan|daterange', 'items.ccode',
118 'items.itemcallnumber|textrange', 'items.itype', 'items.itemlost',
120 PAT => [ 'borrowers.branchcode', 'borrowers.categorycode' ],
121 ACQ => ['aqorders.datereceived|date'],
122 ACC => [ 'borrowers.branchcode', 'borrowers.categorycode' ],
125 # Adds itemtypes to criteria, according to the syspref
126 if ( C4::Context->preference('item-level_itypes') ) {
127 unshift @{ $criteria{'CIRC'} }, 'items.itype';
128 unshift @{ $criteria{'CAT'} }, 'items.itype';
130 unshift @{ $criteria{'CIRC'} }, 'biblioitems.itemtype';
131 unshift @{ $criteria{'CAT'} }, 'biblioitems.itemtype';
134 =head2 get_report_types
136 This will return a list of all the available report types
140 sub get_report_types {
141 my $dbh = C4::Context->dbh();
143 # FIXME these should be in the database perhaps
144 my @reports = ( 'Tabular', 'Summary', 'Matrix' );
146 for ( my $i = 0 ; $i < 3 ; $i++ ) {
148 $hashrep{id} = $i + 1;
149 $hashrep{name} = $reports[$i];
150 push @reports2, \%hashrep;
152 return ( \@reports2 );
156 =head2 get_report_groups
158 This will return a list of all the available report areas with groups
162 sub get_report_groups {
163 my $dbh = C4::Context->dbh();
165 my $groups = GetAuthorisedValues('REPORT_GROUP');
166 my $subgroups = GetAuthorisedValues('REPORT_SUBGROUP');
168 my %groups_with_subgroups = map { $_->{authorised_value} => {
172 foreach (@$subgroups) {
173 my $sg = $_->{authorised_value};
174 my $g = $_->{lib_opac}
175 or warn( qq{REPORT_SUBGROUP "$sg" without REPORT_GROUP (lib_opac)} ),
177 my $g_sg = $groups_with_subgroups{$g}
178 or warn( qq{REPORT_SUBGROUP "$sg" with invalid REPORT_GROUP "$g"} ),
180 $g_sg->{subgroups}{$sg} = $_->{lib};
182 return \%groups_with_subgroups
185 =head2 get_all_tables
187 This will return a list of all tables in the database
192 my $dbh = C4::Context->dbh();
193 my $query = "SHOW TABLES";
194 my $sth = $dbh->prepare($query);
197 while ( my $data = $sth->fetchrow_arrayref() ) {
198 push @tables, $data->[0];
205 =head2 get_columns($area)
207 This will return a list of all columns for a report area
213 # this calls the internal fucntion _get_columns
214 my ( $area, $cgi ) = @_;
215 my $tables = $table_areas{$area}
216 or die qq{Unsuported report area "$area"};
220 foreach my $table (@$tables) {
221 my @columns = _get_columns($table,$cgi, $first);
223 push @allcolumns, @columns;
225 return ( \@allcolumns );
229 my ($tablename,$cgi, $first) = @_;
230 my $dbh = C4::Context->dbh();
231 my $sth = $dbh->prepare("show columns from $tablename");
234 my $column_defs = _get_column_defs($cgi);
236 $tablehash{'table'}=$tablename;
237 $tablehash{'__first__'} = $first;
238 push @columns, \%tablehash;
239 while ( my $data = $sth->fetchrow_arrayref() ) {
241 $temphash{'name'} = "$tablename.$data->[0]";
242 $temphash{'description'} = $column_defs->{"$tablename.$data->[0]"};
243 push @columns, \%temphash;
249 =head2 build_query($columns,$criteria,$orderby,$area)
251 This will build the sql needed to return the results asked for,
252 $columns is expected to be of the format tablename.columnname.
253 This is what get_columns returns.
258 my ( $columns, $criteria, $orderby, $area, $totals, $definition ) = @_;
260 my $keys = $keys{$area};
261 my $tables = $table_areas{$area};
264 _build_query( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition );
269 my ( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition) = @_;
271 # $keys is an array of joining constraints
272 my $dbh = C4::Context->dbh();
273 my $joinedtables = join( ',', @$tables );
274 my $joinedcolumns = join( ',', @$columns );
276 "SELECT $totals $joinedcolumns FROM $tables->[0] ";
277 for (my $i=1;$i<@$tables;$i++){
278 $query .= "LEFT JOIN $tables->[$i] on ($keys->[$i-1]) ";
282 $criteria =~ s/AND/WHERE/;
283 $query .= " $criteria";
286 my @definitions = split(',',$definition);
288 foreach my $def (@definitions){
289 my $defin=get_from_dictionary('',$def);
290 $deftext .=" ".$defin->[0]->{'saved_sql'};
292 if ($query =~ /WHERE/i){
296 $deftext =~ s/AND/WHERE/;
302 my @totcolumns = split( ',', $totals );
303 foreach my $total (@totcolumns) {
304 if ( $total =~ /\((.*)\)/ ) {
305 if ( $groupby eq '' ) {
306 $groupby = " GROUP BY $1";
321 =head2 get_criteria($area,$cgi);
323 Returns an arraref to hashrefs suitable for using in a tmpl_loop. With the criteria and available values.
328 my ($area,$cgi) = @_;
329 my $dbh = C4::Context->dbh();
330 my $crit = $criteria{$area};
331 my $column_defs = _get_column_defs($cgi);
333 foreach my $localcrit (@$crit) {
334 my ( $value, $type ) = split( /\|/, $localcrit );
335 my ( $table, $column ) = split( /\./, $value );
336 if ($type eq 'textrange') {
338 $temp{'name'} = $value;
339 $temp{'from'} = "from_" . $value;
340 $temp{'to'} = "to_" . $value;
341 $temp{'textrange'} = 1;
342 $temp{'description'} = $column_defs->{$value};
343 push @criteria_array, \%temp;
345 elsif ($type eq 'date') {
347 $temp{'name'} = $value;
349 $temp{'description'} = $column_defs->{$value};
350 push @criteria_array, \%temp;
352 elsif ($type eq 'daterange') {
354 $temp{'name'} = $value;
355 $temp{'from'} = "from_" . $value;
356 $temp{'to'} = "to_" . $value;
357 $temp{'daterange'} = 1;
358 $temp{'description'} = $column_defs->{$value};
359 push @criteria_array, \%temp;
363 "SELECT distinct($column) as availablevalues FROM $table";
364 my $sth = $dbh->prepare($query);
367 # push the runtime choosing option
369 $list='branches' if $column eq 'branchcode' or $column eq 'holdingbranch' or $column eq 'homebranch';
370 $list='categorycode' if $column eq 'categorycode';
371 $list='itemtype' if $column eq 'itype';
372 $list='ccode' if $column eq 'ccode';
373 # TODO : improve to let the librarian choose the description at runtime
374 push @values, { availablevalues => "<<$column".($list?"|$list":'').">>" };
375 while ( my $row = $sth->fetchrow_hashref() ) {
377 if ($row->{'availablevalues'} eq '') { $row->{'default'} = 1 };
382 $temp{'name'} = $value;
383 $temp{'description'} = $column_defs->{$value};
384 $temp{'values'} = \@values;
386 push @criteria_array, \%temp;
390 return ( \@criteria_array );
394 my $sql = shift or return;
395 my $sth = C4::Context->dbh->prepare($sql);
397 my $rows = $sth->fetchall_arrayref();
398 return scalar (@$rows);
403 ($sth, $error) = execute_query($sql, $offset, $limit[, \@sql_params])
406 This function returns a DBI statement handler from which the caller can
407 fetch the results of the SQL passed via C<$sql>.
409 If passed any query other than a SELECT, or if there is a db error,
410 C<$errors> an array ref is returned containing the error after this
413 C<$error->{'sqlerr'}> contains the offending SQL keyword.
414 C<$error->{'queryerr'}> contains the native db engine error returned
417 C<$offset>, and C<$limit> are required parameters.
419 C<\@sql_params> is an optional list of parameter values to paste in.
420 The caller is reponsible for making sure that C<$sql> has placeholders
421 and that the number placeholders matches the number of parameters.
425 # returns $sql, $offset, $limit
426 # $sql returned will be transformed to:
427 # ~ remove any LIMIT clause
428 # ~ repace SELECT clause w/ SELECT count(*)
430 sub select_2_select_count {
431 # Modify the query passed in to create a count query... (I think this covers all cases -crn)
432 my ($sql) = strip_limit(shift) or return;
433 $sql =~ s/\bSELECT\W+(?:\w+\W+){1,}?FROM\b|\bSELECT\W\*\WFROM\b/SELECT count(*) FROM /ig;
437 # This removes the LIMIT from the query so that a custom one can be specified.
439 # ($new_sql, $offset, $limit) = strip_limit($sql);
442 # $sql is the query to modify
443 # $new_sql is the resulting query
444 # $offset is the offset value, if the LIMIT was the two-argument form,
445 # 0 if it wasn't otherwise given.
446 # $limit is the limit value
449 # * This makes an effort to not break subqueries that have their own
450 # LIMIT specified. It does that by only removing a LIMIT if it comes after
451 # a WHERE clause (which isn't perfect, but at least should make more cases
452 # work - subqueries with a limit in the WHERE will still break.)
453 # * If your query doesn't have a WHERE clause then all LIMITs will be
454 # removed. This may break some subqueries, but is hopefully rare enough
455 # to not be a big issue.
460 return ($sql, 0, undef) unless $sql =~ /\bLIMIT\b/i;
462 # Two options: if there's no WHERE clause in the SQL, we simply capture
463 # any LIMIT that's there. If there is a WHERE, we make sure that we only
464 # capture a LIMIT after the last one. This prevents stomping on subqueries.
465 if ($sql !~ /\bWHERE\b/i) {
466 (my $res = $sql) =~ s/\bLIMIT\b\s*(\d+)(\s*\,\s*(\d+))?\s*/ /ig;
467 return ($res, (defined $2 ? $1 : 0), (defined $3 ? $3 : $1));
470 $res =~ m/.*\bWHERE\b/gsi;
471 $res =~ s/\G(.*)\bLIMIT\b\s*(\d+)(\s*\,\s*(\d+))?\s*/$1 /is;
472 return ($res, (defined $3 ? $2 : 0), (defined $4 ? $4 : $2));
478 my ( $sql, $offset, $limit, $sql_params ) = @_;
480 $sql_params = [] unless defined $sql_params;
484 carp "execute_query() called without SQL argument";
487 $offset = 0 unless $offset;
488 $limit = 999999 unless $limit;
489 $debug and print STDERR "execute_query($sql, $offset, $limit)\n";
490 if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
491 return (undef, { sqlerr => $1} );
492 } elsif ($sql !~ /^\s*SELECT\b\s*/i) {
493 return (undef, { queryerr => 'Missing SELECT'} );
496 my ($useroffset, $userlimit);
498 # Grab offset/limit from user supplied LIMIT and drop the LIMIT so we can control pagination
499 ($sql, $useroffset, $userlimit) = strip_limit($sql);
500 $debug and warn sprintf "User has supplied (OFFSET,) LIMIT = %s, %s",
502 (defined($userlimit ) ? $userlimit : 'UNDEF');
503 $offset += $useroffset;
504 if (defined($userlimit)) {
505 if ($offset + $limit > $userlimit ) {
506 $limit = $userlimit - $offset;
507 } elsif ( ! $offset && $limit < $userlimit ) {
511 $sql .= " LIMIT ?, ?";
513 my $sth = C4::Context->dbh->prepare($sql);
514 $sth->execute(@$sql_params, $offset, $limit);
515 return ( $sth, { queryerr => $sth->errstr } ) if ($sth->err);
517 # my @xmlarray = ... ;
518 # my $url = "/cgi-bin/koha/reports/guided_reports.pl?phase=retrieve%20results&id=$id";
519 # my $xml = XML::Dumper->new()->pl2xml( \@xmlarray );
520 # store_results($id,$xml);
523 =head2 save_report($sql,$name,$type,$notes)
525 Given some sql and a name this will saved it so that it can reused
526 Returns id of the newly created report
532 my $borrowernumber = $fields->{borrowernumber};
533 my $sql = $fields->{sql};
534 my $name = $fields->{name};
535 my $type = $fields->{type};
536 my $notes = $fields->{notes};
537 my $area = $fields->{area};
538 my $group = $fields->{group};
539 my $subgroup = $fields->{subgroup};
540 my $cache_expiry = $fields->{cache_expiry} || 300;
541 my $public = $fields->{public};
543 my $dbh = C4::Context->dbh();
544 $sql =~ s/(\s*\;\s*)$//; # removes trailing whitespace and /;/
545 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(),?,?,?,?,?,?,?,?,?)";
546 $dbh->do($query, undef, $borrowernumber, $sql, $name, $area, $group, $subgroup, $type, $notes, $cache_expiry, $public);
548 my $id = $dbh->selectrow_array("SELECT max(id) FROM saved_sql WHERE borrowernumber=? AND report_name=?", undef,
549 $borrowernumber, $name);
554 my $id = shift || croak "No Id given";
556 my $sql = $fields->{sql};
557 my $name = $fields->{name};
558 my $notes = $fields->{notes};
559 my $group = $fields->{group};
560 my $subgroup = $fields->{subgroup};
561 my $cache_expiry = $fields->{cache_expiry};
562 my $public = $fields->{public};
564 if( $cache_expiry >= 2592000 ){
565 die "Please specify a cache expiry less than 30 days\n";
568 my $dbh = C4::Context->dbh();
569 $sql =~ s/(\s*\;\s*)$//; # removes trailing whitespace and /;/
570 my $query = "UPDATE saved_sql SET savedsql = ?, last_modified = now(), report_name = ?, report_group = ?, report_subgroup = ?, notes = ?, cache_expiry = ?, public = ? WHERE id = ? ";
571 $dbh->do($query, undef, $sql, $name, $group, $subgroup, $notes, $cache_expiry, $public, $id );
576 my $dbh = C4::Context->dbh();
577 my $query = "SELECT * FROM saved_reports WHERE report_id=?";
578 my $sth = $dbh->prepare($query);
580 if (my $data=$sth->fetchrow_hashref()){
581 my $query2 = "UPDATE saved_reports SET report=?,date_run=now() WHERE report_id=?";
582 my $sth2 = $dbh->prepare($query2);
583 $sth2->execute($xml,$id);
586 my $query2 = "INSERT INTO saved_reports (report_id,report,date_run) VALUES (?,?,now())";
587 my $sth2 = $dbh->prepare($query2);
588 $sth2->execute($id,$xml);
594 my $dbh = C4::Context->dbh();
595 my $query = "SELECT * FROM saved_reports WHERE report_id = ?";
596 my $sth = $dbh->prepare($query);
598 my $data = $sth->fetchrow_hashref();
599 my $dump = new XML::Dumper;
600 my $perl = $dump->xml2pl( $data->{'report'} );
601 foreach my $row (@$perl) {
603 foreach my $key (keys %$row){
604 $htmlrow .= "<td>$row->{$key}</td>";
607 $row->{'row'} = $htmlrow;
610 $query = "SELECT * FROM saved_sql WHERE id = ?";
611 $sth = $dbh->prepare($query);
613 $data = $sth->fetchrow_hashref();
614 return ($perl,$data->{'report_name'},$data->{'notes'});
620 my $dbh = C4::Context->dbh;
621 my $query = 'DELETE FROM saved_sql WHERE id IN (' . join( ',', ('?') x @ids ) . ')';
622 my $sth = $dbh->prepare($query);
623 return $sth->execute(@ids);
626 my $SAVED_REPORTS_BASE_QRY = <<EOQ;
627 SELECT s.*, r.report, r.date_run, $AREA_NAME_SQL_SNIPPET, av_g.lib AS groupname, av_sg.lib AS subgroupname,
628 b.firstname AS borrowerfirstname, b.surname AS borrowersurname
630 LEFT JOIN saved_reports r ON r.report_id = s.id
631 LEFT OUTER JOIN authorised_values av_g ON (av_g.category = 'REPORT_GROUP' AND av_g.authorised_value = s.report_group)
632 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)
633 LEFT OUTER JOIN borrowers b USING (borrowernumber)
635 my $DATE_FORMAT = "%d/%m/%Y";
636 sub get_saved_reports {
637 # $filter is either { date => $d, author => $a, keyword => $kw, }
638 # or $keyword. Optional.
640 $filter = { keyword => $filter } if $filter && !ref( $filter );
641 my ($group, $subgroup) = @_;
643 my $dbh = C4::Context->dbh();
644 my $query = $SAVED_REPORTS_BASE_QRY;
647 if (my $date = $filter->{date}) {
648 $date = format_date_in_iso($date);
649 push @cond, "DATE(date_run) = ? OR
650 DATE(date_created) = ? OR
651 DATE(last_modified) = ? OR
653 push @args, $date, $date, $date, $date;
655 if (my $author = $filter->{author}) {
656 $author = "%$author%";
657 push @cond, "surname LIKE ? OR
659 push @args, $author, $author;
661 if (my $keyword = $filter->{keyword}) {
662 $keyword = "%$keyword%";
663 push @cond, "report LIKE ? OR
664 report_name LIKE ? OR
667 push @args, $keyword, $keyword, $keyword, $keyword;
669 if ($filter->{group}) {
670 push @cond, "report_group = ?";
671 push @args, $filter->{group};
673 if ($filter->{subgroup}) {
674 push @cond, "report_subgroup = ?";
675 push @args, $filter->{subgroup};
678 $query .= " WHERE ".join( " AND ", map "($_)", @cond ) if @cond;
679 $query .= " ORDER by date_created";
681 my $result = $dbh->selectall_arrayref($query, {Slice => {}}, @args);
686 sub get_saved_report {
687 my $dbh = C4::Context->dbh();
690 if ($#_ == 0 && ref $_[0] ne 'HASH') {
692 $query = " SELECT * FROM saved_sql WHERE id = ?";
693 } elsif (ref $_[0] eq 'HASH') {
695 if ($selector->{name}) {
696 $query = " SELECT * FROM saved_sql WHERE report_name = ?";
697 $report_arg = $selector->{name};
698 } elsif ($selector->{id} || $selector->{id} eq '0') {
699 $query = " SELECT * FROM saved_sql WHERE id = ?";
700 $report_arg = $selector->{id};
707 return $dbh->selectrow_hashref($query, undef, $report_arg);
710 =head2 create_compound($masterID,$subreportID)
712 This will take 2 reports and create a compound report using both of them
716 sub create_compound {
717 my ( $masterID, $subreportID ) = @_;
718 my $dbh = C4::Context->dbh();
721 my $master = get_saved_report($masterID);
722 my $mastersql = $master->{savedsql};
723 my $mastertype = $master->{type};
724 my $sub = get_saved_report($subreportID);
725 my $subsql = $master->{savedsql};
726 my $subtype = $master->{type};
728 # now we have to do some checking to see how these two will fit together
730 my ( $mastertables, $subtables );
731 if ( $mastersql =~ / from (.*) where /i ) {
734 if ( $subsql =~ / from (.*) where /i ) {
737 return ( $mastertables, $subtables );
740 =head2 get_column_type($column)
742 This takes a column name of the format table.column and will return what type it is
743 (free text, set values, date)
747 sub get_column_type {
748 my ($tablecolumn) = @_;
749 my ($table,$column) = split(/\./,$tablecolumn);
750 my $dbh = C4::Context->dbh();
754 # mysql doesnt support a column selection, set column to %
756 my $sth = $dbh->column_info( $catalog, $schema, $table, $tempcolumn ) || die $dbh->errstr;
757 while (my $info = $sth->fetchrow_hashref()){
758 if ($info->{'COLUMN_NAME'} eq $column){
760 if ($info->{'TYPE_NAME'} eq 'CHAR' || $info->{'TYPE_NAME'} eq 'VARCHAR'){
761 $info->{'TYPE_NAME'} = 'distinct';
763 return $info->{'TYPE_NAME'};
768 =head2 get_distinct_values($column)
770 Given a column name, return an arrary ref of hashrefs suitable for use as a tmpl_loop
771 with the distinct values of the column
775 sub get_distinct_values {
776 my ($tablecolumn) = @_;
777 my ($table,$column) = split(/\./,$tablecolumn);
778 my $dbh = C4::Context->dbh();
780 "SELECT distinct($column) as availablevalues FROM $table";
781 my $sth = $dbh->prepare($query);
783 return $sth->fetchall_arrayref({});
786 sub save_dictionary {
787 my ( $name, $description, $sql, $area ) = @_;
788 my $dbh = C4::Context->dbh();
789 my $query = "INSERT INTO reports_dictionary (name,description,saved_sql,report_area,date_created,date_modified)
790 VALUES (?,?,?,?,now(),now())";
791 my $sth = $dbh->prepare($query);
792 $sth->execute($name,$description,$sql,$area) || return 0;
796 my $DICTIONARY_BASE_QRY = <<EOQ;
797 SELECT d.*, $AREA_NAME_SQL_SNIPPET
798 FROM reports_dictionary d
800 sub get_from_dictionary {
801 my ( $area, $id ) = @_;
802 my $dbh = C4::Context->dbh();
803 my $query = $DICTIONARY_BASE_QRY;
805 $query .= " WHERE report_area = ?";
807 $query .= " WHERE id = ?";
809 my $sth = $dbh->prepare($query);
813 $sth->execute($area);
818 while ( my $data = $sth->fetchrow_hashref() ) {
824 sub delete_definition {
825 my ($id) = @_ or return;
826 my $dbh = C4::Context->dbh();
827 my $query = "DELETE FROM reports_dictionary WHERE id = ?";
828 my $sth = $dbh->prepare($query);
833 my ($id) = @_ or return;
834 my $dbh = C4::Context->dbh();
835 my $query = "SELECT * FROM saved_sql WHERE id = ?";
836 my $sth = $dbh->prepare($query);
838 my $data=$sth->fetchrow_hashref();
839 return $data->{'savedsql'};
842 sub _get_column_defs {
845 my $columns_def_file = "columns.def";
846 my $htdocs = C4::Context->config('intrahtdocs');
847 my $section = 'intranet';
849 # We need the theme and the lang
850 # Since columns.def is not in the modules directory, we cannot sent it for the $tmpl var
851 my ($theme, $lang, $availablethemes) = C4::Templates::themelanguage($htdocs, 'about.tt', $section, $cgi);
853 my $full_path_to_columns_def_file="$htdocs/$theme/$lang/$columns_def_file";
854 open (my $fh, $full_path_to_columns_def_file);
855 while ( my $input = <$fh> ){
857 if ( $input =~ m|<field name="(.*)">(.*)</field>| ) {
858 my ( $field, $translation ) = ( $1, $2 );
859 $columns{$field} = $translation;
866 =head2 build_authorised_value_list($authorised_value)
868 Returns an arrayref - hashref pair. The hashref consists of
869 various code => name lists depending on the $authorised_value.
870 The arrayref is the hashref keys, in appropriate order
874 sub build_authorised_value_list {
875 my ( $authorised_value ) = @_;
877 my $dbh = C4::Context->dbh;
878 my @authorised_values;
881 # builds list, depending on authorised value...
882 if ( $authorised_value eq "branches" ) {
883 my $branches = GetBranchesLoop();
884 foreach my $thisbranch (@$branches) {
885 push @authorised_values, $thisbranch->{value};
886 $authorised_lib{ $thisbranch->{value} } = $thisbranch->{branchname};
888 } elsif ( $authorised_value eq "itemtypes" ) {
889 my $sth = $dbh->prepare("SELECT itemtype,description FROM itemtypes ORDER BY description");
891 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
892 push @authorised_values, $itemtype;
893 $authorised_lib{$itemtype} = $description;
895 } elsif ( $authorised_value eq "cn_source" ) {
896 my $class_sources = GetClassSources();
897 my $default_source = C4::Context->preference("DefaultClassificationSource");
898 foreach my $class_source ( sort keys %$class_sources ) {
900 unless $class_sources->{$class_source}->{'used'}
901 or ( $class_source eq $default_source );
902 push @authorised_values, $class_source;
903 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
905 } elsif ( $authorised_value eq "categorycode" ) {
906 my $sth = $dbh->prepare("SELECT categorycode, description FROM categories ORDER BY description");
908 while ( my ( $categorycode, $description ) = $sth->fetchrow_array ) {
909 push @authorised_values, $categorycode;
910 $authorised_lib{$categorycode} = $description;
913 #---- "true" authorised value
915 my $authorised_values_sth = $dbh->prepare("SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib");
917 $authorised_values_sth->execute($authorised_value);
919 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
920 push @authorised_values, $value;
921 $authorised_lib{$value} = $lib;
923 # For item location, we show the code and the libelle
924 $authorised_lib{$value} = $lib;
928 return (\@authorised_values, \%authorised_lib);
931 =head2 GetReservedAuthorisedValues
933 my %reserved_authorised_values = GetReservedAuthorisedValues();
935 Returns a hash containig all reserved words
939 sub GetReservedAuthorisedValues {
940 my %reserved_authorised_values =
941 map { $_ => 1 } ( 'date',
947 return \%reserved_authorised_values;
951 =head2 IsAuthorisedValueValid
953 my $is_valid_ath_value = IsAuthorisedValueValid($authorised_value)
955 Returns 1 if $authorised_value is on the reserved authorised values list or
956 in the authorised value categories defined in
960 sub IsAuthorisedValueValid {
962 my $authorised_value = shift;
963 my $reserved_authorised_values = GetReservedAuthorisedValues();
965 if ( exists $reserved_authorised_values->{$authorised_value} ||
966 IsAuthorisedValueCategory($authorised_value) ) {
973 =head2 GetParametersFromSQL
975 my @sql_parameters = GetParametersFromSQL($sql)
977 Returns an arrayref of hashes containing the keys name and authval
981 sub GetParametersFromSQL {
984 my @split = split(/<<|>>/,$sql);
985 my @sql_parameters = ();
987 for ( my $i = 0; $i < ($#split/2) ; $i++ ) {
988 my ($name,$authval) = split(/\|/,$split[$i*2+1]);
989 push @sql_parameters, { 'name' => $name, 'authval' => $authval };
992 return \@sql_parameters;
995 =head2 ValidateSQLParameters
997 my @problematic_parameters = ValidateSQLParameters($sql)
999 Returns an arrayref of hashes containing the keys name and authval of
1000 those SQL parameters that do not correspond to valid authorised names
1004 sub ValidateSQLParameters {
1007 my @problematic_parameters = ();
1008 my $sql_parameters = GetParametersFromSQL($sql);
1010 foreach my $sql_parameter (@$sql_parameters) {
1011 if ( defined $sql_parameter->{'authval'} ) {
1012 push @problematic_parameters, $sql_parameter unless
1013 IsAuthorisedValueValid($sql_parameter->{'authval'});
1017 return \@problematic_parameters;
1025 Chris Cormack <crc@liblime.com>