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);
516 # my @xmlarray = ... ;
517 # my $url = "/cgi-bin/koha/reports/guided_reports.pl?phase=retrieve%20results&id=$id";
518 # my $xml = XML::Dumper->new()->pl2xml( \@xmlarray );
519 # store_results($id,$xml);
522 =head2 save_report($sql,$name,$type,$notes)
524 Given some sql and a name this will saved it so that it can reused
525 Returns id of the newly created report
531 my $borrowernumber = $fields->{borrowernumber};
532 my $sql = $fields->{sql};
533 my $name = $fields->{name};
534 my $type = $fields->{type};
535 my $notes = $fields->{notes};
536 my $area = $fields->{area};
537 my $group = $fields->{group};
538 my $subgroup = $fields->{subgroup};
539 my $cache_expiry = $fields->{cache_expiry} || 300;
540 my $public = $fields->{public};
542 my $dbh = C4::Context->dbh();
543 $sql =~ s/(\s*\;\s*)$//; # removes trailing whitespace and /;/
544 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(),?,?,?,?,?,?,?,?,?)";
545 $dbh->do($query, undef, $borrowernumber, $sql, $name, $area, $group, $subgroup, $type, $notes, $cache_expiry, $public);
547 my $id = $dbh->selectrow_array("SELECT max(id) FROM saved_sql WHERE borrowernumber=? AND report_name=?", undef,
548 $borrowernumber, $name);
553 my $id = shift || croak "No Id given";
555 my $sql = $fields->{sql};
556 my $name = $fields->{name};
557 my $notes = $fields->{notes};
558 my $group = $fields->{group};
559 my $subgroup = $fields->{subgroup};
560 my $cache_expiry = $fields->{cache_expiry};
561 my $public = $fields->{public};
563 if( $cache_expiry >= 2592000 ){
564 die "Please specify a cache expiry less than 30 days\n";
567 my $dbh = C4::Context->dbh();
568 $sql =~ s/(\s*\;\s*)$//; # removes trailing whitespace and /;/
569 my $query = "UPDATE saved_sql SET savedsql = ?, last_modified = now(), report_name = ?, report_group = ?, report_subgroup = ?, notes = ?, cache_expiry = ?, public = ? WHERE id = ? ";
570 $dbh->do($query, undef, $sql, $name, $group, $subgroup, $notes, $cache_expiry, $public, $id );
575 my $dbh = C4::Context->dbh();
576 my $query = "SELECT * FROM saved_reports WHERE report_id=?";
577 my $sth = $dbh->prepare($query);
579 if (my $data=$sth->fetchrow_hashref()){
580 my $query2 = "UPDATE saved_reports SET report=?,date_run=now() WHERE report_id=?";
581 my $sth2 = $dbh->prepare($query2);
582 $sth2->execute($xml,$id);
585 my $query2 = "INSERT INTO saved_reports (report_id,report,date_run) VALUES (?,?,now())";
586 my $sth2 = $dbh->prepare($query2);
587 $sth2->execute($id,$xml);
593 my $dbh = C4::Context->dbh();
594 my $query = "SELECT * FROM saved_reports WHERE report_id = ?";
595 my $sth = $dbh->prepare($query);
597 my $data = $sth->fetchrow_hashref();
598 my $dump = new XML::Dumper;
599 my $perl = $dump->xml2pl( $data->{'report'} );
600 foreach my $row (@$perl) {
602 foreach my $key (keys %$row){
603 $htmlrow .= "<td>$row->{$key}</td>";
606 $row->{'row'} = $htmlrow;
609 $query = "SELECT * FROM saved_sql WHERE id = ?";
610 $sth = $dbh->prepare($query);
612 $data = $sth->fetchrow_hashref();
613 return ($perl,$data->{'report_name'},$data->{'notes'});
619 my $dbh = C4::Context->dbh;
620 my $query = 'DELETE FROM saved_sql WHERE id IN (' . join( ',', ('?') x @ids ) . ')';
621 my $sth = $dbh->prepare($query);
622 return $sth->execute(@ids);
625 my $SAVED_REPORTS_BASE_QRY = <<EOQ;
626 SELECT s.*, r.report, r.date_run, $AREA_NAME_SQL_SNIPPET, av_g.lib AS groupname, av_sg.lib AS subgroupname,
627 b.firstname AS borrowerfirstname, b.surname AS borrowersurname
629 LEFT JOIN saved_reports r ON r.report_id = s.id
630 LEFT OUTER JOIN authorised_values av_g ON (av_g.category = 'REPORT_GROUP' AND av_g.authorised_value = s.report_group)
631 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)
632 LEFT OUTER JOIN borrowers b USING (borrowernumber)
634 my $DATE_FORMAT = "%d/%m/%Y";
635 sub get_saved_reports {
636 # $filter is either { date => $d, author => $a, keyword => $kw, }
637 # or $keyword. Optional.
639 $filter = { keyword => $filter } if $filter && !ref( $filter );
640 my ($group, $subgroup) = @_;
642 my $dbh = C4::Context->dbh();
643 my $query = $SAVED_REPORTS_BASE_QRY;
646 if (my $date = $filter->{date}) {
647 $date = format_date_in_iso($date);
648 push @cond, "DATE(date_run) = ? OR
649 DATE(date_created) = ? OR
650 DATE(last_modified) = ? OR
652 push @args, $date, $date, $date, $date;
654 if (my $author = $filter->{author}) {
655 $author = "%$author%";
656 push @cond, "surname LIKE ? OR
658 push @args, $author, $author;
660 if (my $keyword = $filter->{keyword}) {
661 $keyword = "%$keyword%";
662 push @cond, "report LIKE ? OR
663 report_name LIKE ? OR
666 push @args, $keyword, $keyword, $keyword, $keyword;
668 if ($filter->{group}) {
669 push @cond, "report_group = ?";
670 push @args, $filter->{group};
672 if ($filter->{subgroup}) {
673 push @cond, "report_subgroup = ?";
674 push @args, $filter->{subgroup};
677 $query .= " WHERE ".join( " AND ", map "($_)", @cond ) if @cond;
678 $query .= " ORDER by date_created";
680 my $result = $dbh->selectall_arrayref($query, {Slice => {}}, @args);
685 sub get_saved_report {
686 my $dbh = C4::Context->dbh();
689 if ($#_ == 0 && ref $_[0] ne 'HASH') {
691 $query = " SELECT * FROM saved_sql WHERE id = ?";
692 } elsif (ref $_[0] eq 'HASH') {
694 if ($selector->{name}) {
695 $query = " SELECT * FROM saved_sql WHERE report_name = ?";
696 $report_arg = $selector->{name};
697 } elsif ($selector->{id} || $selector->{id} eq '0') {
698 $query = " SELECT * FROM saved_sql WHERE id = ?";
699 $report_arg = $selector->{id};
706 return $dbh->selectrow_hashref($query, undef, $report_arg);
709 =head2 create_compound($masterID,$subreportID)
711 This will take 2 reports and create a compound report using both of them
715 sub create_compound {
716 my ( $masterID, $subreportID ) = @_;
717 my $dbh = C4::Context->dbh();
720 my $master = get_saved_report($masterID);
721 my $mastersql = $master->{savedsql};
722 my $mastertype = $master->{type};
723 my $sub = get_saved_report($subreportID);
724 my $subsql = $master->{savedsql};
725 my $subtype = $master->{type};
727 # now we have to do some checking to see how these two will fit together
729 my ( $mastertables, $subtables );
730 if ( $mastersql =~ / from (.*) where /i ) {
733 if ( $subsql =~ / from (.*) where /i ) {
736 return ( $mastertables, $subtables );
739 =head2 get_column_type($column)
741 This takes a column name of the format table.column and will return what type it is
742 (free text, set values, date)
746 sub get_column_type {
747 my ($tablecolumn) = @_;
748 my ($table,$column) = split(/\./,$tablecolumn);
749 my $dbh = C4::Context->dbh();
753 # mysql doesnt support a column selection, set column to %
755 my $sth = $dbh->column_info( $catalog, $schema, $table, $tempcolumn ) || die $dbh->errstr;
756 while (my $info = $sth->fetchrow_hashref()){
757 if ($info->{'COLUMN_NAME'} eq $column){
759 if ($info->{'TYPE_NAME'} eq 'CHAR' || $info->{'TYPE_NAME'} eq 'VARCHAR'){
760 $info->{'TYPE_NAME'} = 'distinct';
762 return $info->{'TYPE_NAME'};
767 =head2 get_distinct_values($column)
769 Given a column name, return an arrary ref of hashrefs suitable for use as a tmpl_loop
770 with the distinct values of the column
774 sub get_distinct_values {
775 my ($tablecolumn) = @_;
776 my ($table,$column) = split(/\./,$tablecolumn);
777 my $dbh = C4::Context->dbh();
779 "SELECT distinct($column) as availablevalues FROM $table";
780 my $sth = $dbh->prepare($query);
782 return $sth->fetchall_arrayref({});
785 sub save_dictionary {
786 my ( $name, $description, $sql, $area ) = @_;
787 my $dbh = C4::Context->dbh();
788 my $query = "INSERT INTO reports_dictionary (name,description,saved_sql,report_area,date_created,date_modified)
789 VALUES (?,?,?,?,now(),now())";
790 my $sth = $dbh->prepare($query);
791 $sth->execute($name,$description,$sql,$area) || return 0;
795 my $DICTIONARY_BASE_QRY = <<EOQ;
796 SELECT d.*, $AREA_NAME_SQL_SNIPPET
797 FROM reports_dictionary d
799 sub get_from_dictionary {
800 my ( $area, $id ) = @_;
801 my $dbh = C4::Context->dbh();
802 my $query = $DICTIONARY_BASE_QRY;
804 $query .= " WHERE report_area = ?";
806 $query .= " WHERE id = ?";
808 my $sth = $dbh->prepare($query);
812 $sth->execute($area);
817 while ( my $data = $sth->fetchrow_hashref() ) {
823 sub delete_definition {
824 my ($id) = @_ or return;
825 my $dbh = C4::Context->dbh();
826 my $query = "DELETE FROM reports_dictionary WHERE id = ?";
827 my $sth = $dbh->prepare($query);
832 my ($id) = @_ or return;
833 my $dbh = C4::Context->dbh();
834 my $query = "SELECT * FROM saved_sql WHERE id = ?";
835 my $sth = $dbh->prepare($query);
837 my $data=$sth->fetchrow_hashref();
838 return $data->{'savedsql'};
841 sub _get_column_defs {
844 my $columns_def_file = "columns.def";
845 my $htdocs = C4::Context->config('intrahtdocs');
846 my $section = 'intranet';
848 # We need the theme and the lang
849 # Since columns.def is not in the modules directory, we cannot sent it for the $tmpl var
850 my ($theme, $lang, $availablethemes) = C4::Templates::themelanguage($htdocs, 'about.tt', $section, $cgi);
852 my $full_path_to_columns_def_file="$htdocs/$theme/$lang/$columns_def_file";
853 open (my $fh, $full_path_to_columns_def_file);
854 while ( my $input = <$fh> ){
856 if ( $input =~ m|<field name="(.*)">(.*)</field>| ) {
857 my ( $field, $translation ) = ( $1, $2 );
858 $columns{$field} = $translation;
865 =head2 build_authorised_value_list($authorised_value)
867 Returns an arrayref - hashref pair. The hashref consists of
868 various code => name lists depending on the $authorised_value.
869 The arrayref is the hashref keys, in appropriate order
873 sub build_authorised_value_list {
874 my ( $authorised_value ) = @_;
876 my $dbh = C4::Context->dbh;
877 my @authorised_values;
880 # builds list, depending on authorised value...
881 if ( $authorised_value eq "branches" ) {
882 my $branches = GetBranchesLoop();
883 foreach my $thisbranch (@$branches) {
884 push @authorised_values, $thisbranch->{value};
885 $authorised_lib{ $thisbranch->{value} } = $thisbranch->{branchname};
887 } elsif ( $authorised_value eq "itemtypes" ) {
888 my $sth = $dbh->prepare("SELECT itemtype,description FROM itemtypes ORDER BY description");
890 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
891 push @authorised_values, $itemtype;
892 $authorised_lib{$itemtype} = $description;
894 } elsif ( $authorised_value eq "cn_source" ) {
895 my $class_sources = GetClassSources();
896 my $default_source = C4::Context->preference("DefaultClassificationSource");
897 foreach my $class_source ( sort keys %$class_sources ) {
899 unless $class_sources->{$class_source}->{'used'}
900 or ( $class_source eq $default_source );
901 push @authorised_values, $class_source;
902 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
904 } elsif ( $authorised_value eq "categorycode" ) {
905 my $sth = $dbh->prepare("SELECT categorycode, description FROM categories ORDER BY description");
907 while ( my ( $categorycode, $description ) = $sth->fetchrow_array ) {
908 push @authorised_values, $categorycode;
909 $authorised_lib{$categorycode} = $description;
912 #---- "true" authorised value
914 my $authorised_values_sth = $dbh->prepare("SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib");
916 $authorised_values_sth->execute($authorised_value);
918 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
919 push @authorised_values, $value;
920 $authorised_lib{$value} = $lib;
922 # For item location, we show the code and the libelle
923 $authorised_lib{$value} = $lib;
927 return (\@authorised_values, \%authorised_lib);
930 =head2 GetReservedAuthorisedValues
932 my %reserved_authorised_values = GetReservedAuthorisedValues();
934 Returns a hash containig all reserved words
938 sub GetReservedAuthorisedValues {
939 my %reserved_authorised_values =
940 map { $_ => 1 } ( 'date',
946 return \%reserved_authorised_values;
950 =head2 IsAuthorisedValueValid
952 my $is_valid_ath_value = IsAuthorisedValueValid($authorised_value)
954 Returns 1 if $authorised_value is on the reserved authorised values list or
955 in the authorised value categories defined in
959 sub IsAuthorisedValueValid {
961 my $authorised_value = shift;
962 my $reserved_authorised_values = GetReservedAuthorisedValues();
964 if ( exists $reserved_authorised_values->{$authorised_value} ||
965 IsAuthorisedValueCategory($authorised_value) ) {
972 =head2 GetParametersFromSQL
974 my @sql_parameters = GetParametersFromSQL($sql)
976 Returns an arrayref of hashes containing the keys name and authval
980 sub GetParametersFromSQL {
983 my @split = split(/<<|>>/,$sql);
984 my @sql_parameters = ();
986 for ( my $i = 0; $i < ($#split/2) ; $i++ ) {
987 my ($name,$authval) = split(/\|/,$split[$i*2+1]);
988 push @sql_parameters, { 'name' => $name, 'authval' => $authval };
991 return \@sql_parameters;
994 =head2 ValidateSQLParameters
996 my @problematic_parameters = ValidateSQLParameters($sql)
998 Returns an arrayref of hashes containing the keys name and authval of
999 those SQL parameters that do not correspond to valid authorised names
1003 sub ValidateSQLParameters {
1006 my @problematic_parameters = ();
1007 my $sql_parameters = GetParametersFromSQL($sql);
1009 foreach my $sql_parameter (@$sql_parameters) {
1010 if ( defined $sql_parameter->{'authval'} ) {
1011 push @problematic_parameters, $sql_parameter unless
1012 IsAuthorisedValueValid($sql_parameter->{'authval'});
1016 return \@problematic_parameters;
1024 Chris Cormack <crc@liblime.com>