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>.
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
75 sub get_area_name_sql_snippet
{
77 [CIRC
=> "Circulation"],
80 [ACQ
=> "Acquisition"],
84 return "CASE report_area " .
85 join (" ", map "WHEN '$_->[0]' THEN '$_->[1]'", @REPORT_AREA) .
89 sub get_report_areas
{
91 my $report_areas = [ 'CIRC', 'CAT', 'PAT', 'ACQ', 'ACC' ];
98 CIRC
=> [ 'borrowers', 'statistics', 'items', 'biblioitems' ],
99 CAT
=> [ 'items', 'biblioitems', 'biblio' ],
100 PAT
=> ['borrowers'],
101 ACQ
=> [ 'aqorders', 'biblio', 'items' ],
102 ACC
=> [ 'borrowers', 'accountlines' ],
106 =head2 get_report_types
108 This will return a list of all the available report types
112 sub get_report_types
{
113 my $dbh = C4
::Context
->dbh();
115 # FIXME these should be in the database perhaps
116 my @reports = ( 'Tabular', 'Summary', 'Matrix' );
118 for ( my $i = 0 ; $i < 3 ; $i++ ) {
120 $hashrep{id
} = $i + 1;
121 $hashrep{name
} = $reports[$i];
122 push @reports2, \
%hashrep;
124 return ( \
@reports2 );
128 =head2 get_report_groups
130 This will return a list of all the available report areas with groups
134 sub get_report_groups
{
135 my $dbh = C4
::Context
->dbh();
137 my $groups = GetAuthorisedValues
('REPORT_GROUP');
138 my $subgroups = GetAuthorisedValues
('REPORT_SUBGROUP');
140 my %groups_with_subgroups = map { $_->{authorised_value
} => {
144 foreach (@
$subgroups) {
145 my $sg = $_->{authorised_value
};
146 my $g = $_->{lib_opac
}
147 or warn( qq{REPORT_SUBGROUP
"$sg" without REPORT_GROUP
(lib_opac
)} ),
149 my $g_sg = $groups_with_subgroups{$g}
150 or warn( qq{REPORT_SUBGROUP
"$sg" with invalid REPORT_GROUP
"$g"} ),
152 $g_sg->{subgroups
}{$sg} = $_->{lib
};
154 return \
%groups_with_subgroups
157 =head2 get_all_tables
159 This will return a list of all tables in the database
164 my $dbh = C4
::Context
->dbh();
165 my $query = "SHOW TABLES";
166 my $sth = $dbh->prepare($query);
169 while ( my $data = $sth->fetchrow_arrayref() ) {
170 push @tables, $data->[0];
177 =head2 get_columns($area)
179 This will return a list of all columns for a report area
185 # this calls the internal fucntion _get_columns
186 my ( $area, $cgi ) = @_;
187 my %table_areas = get_table_areas
;
188 my $tables = $table_areas{$area}
189 or die qq{Unsuported report area
"$area"};
193 foreach my $table (@
$tables) {
194 my @columns = _get_columns
($table,$cgi, $first);
196 push @allcolumns, @columns;
198 return ( \
@allcolumns );
202 my ($tablename,$cgi, $first) = @_;
203 my $dbh = C4
::Context
->dbh();
204 my $sth = $dbh->prepare("show columns from $tablename");
207 my $column_defs = _get_column_defs
($cgi);
209 $tablehash{'table'}=$tablename;
210 $tablehash{'__first__'} = $first;
211 push @columns, \
%tablehash;
212 while ( my $data = $sth->fetchrow_arrayref() ) {
214 $temphash{'name'} = "$tablename.$data->[0]";
215 $temphash{'description'} = $column_defs->{"$tablename.$data->[0]"};
216 push @columns, \
%temphash;
222 =head2 build_query($columns,$criteria,$orderby,$area)
224 This will build the sql needed to return the results asked for,
225 $columns is expected to be of the format tablename.columnname.
226 This is what get_columns returns.
231 my ( $columns, $criteria, $orderby, $area, $totals, $definition ) = @_;
234 CIRC
=> [ 'statistics.borrowernumber=borrowers.borrowernumber',
235 'items.itemnumber = statistics.itemnumber',
236 'biblioitems.biblioitemnumber = items.biblioitemnumber' ],
237 CAT
=> [ 'items.biblioitemnumber=biblioitems.biblioitemnumber',
238 'biblioitems.biblionumber=biblio.biblionumber' ],
240 ACQ
=> [ 'aqorders.biblionumber=biblio.biblionumber',
241 'biblio.biblionumber=items.biblionumber' ],
242 ACC
=> ['borrowers.borrowernumber=accountlines.borrowernumber'],
247 my $keys = $keys{$area};
248 my %table_areas = get_table_areas
;
249 my $tables = $table_areas{$area};
252 _build_query
( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition );
257 my ( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition) = @_;
259 # $keys is an array of joining constraints
260 my $dbh = C4
::Context
->dbh();
261 my $joinedtables = join( ',', @
$tables );
262 my $joinedcolumns = join( ',', @
$columns );
264 "SELECT $totals $joinedcolumns FROM $tables->[0] ";
265 for (my $i=1;$i<@
$tables;$i++){
266 $query .= "LEFT JOIN $tables->[$i] on ($keys->[$i-1]) ";
270 $criteria =~ s/AND/WHERE/;
271 $query .= " $criteria";
274 my @definitions = split(',',$definition);
276 foreach my $def (@definitions){
277 my $defin=get_from_dictionary
('',$def);
278 $deftext .=" ".$defin->[0]->{'saved_sql'};
280 if ($query =~ /WHERE/i){
284 $deftext =~ s/AND/WHERE/;
290 my @totcolumns = split( ',', $totals );
291 foreach my $total (@totcolumns) {
292 if ( $total =~ /\((.*)\)/ ) {
293 if ( $groupby eq '' ) {
294 $groupby = " GROUP BY $1";
309 =head2 get_criteria($area,$cgi);
311 Returns an arraref to hashrefs suitable for using in a tmpl_loop. With the criteria and available values.
316 my ($area,$cgi) = @_;
317 my $dbh = C4
::Context
->dbh();
319 # have to do someting here to know if its dropdown, free text, date etc
321 CIRC
=> [ 'statistics.type', 'borrowers.categorycode', 'statistics.branch',
322 'biblioitems.publicationyear|date', 'items.dateaccessioned|date' ],
323 CAT
=> [ 'items.itemnumber|textrange', 'items.biblionumber|textrange',
324 'items.barcode|textrange', 'biblio.frameworkcode',
325 'items.holdingbranch', 'items.homebranch',
326 'biblio.datecreated|daterange', 'biblio.timestamp|daterange',
327 'items.onloan|daterange', 'items.ccode',
328 'items.itemcallnumber|textrange', 'items.itype', 'items.itemlost',
330 PAT
=> [ 'borrowers.branchcode', 'borrowers.categorycode' ],
331 ACQ
=> ['aqorders.datereceived|date'],
332 ACC
=> [ 'borrowers.branchcode', 'borrowers.categorycode' ],
335 # Adds itemtypes to criteria, according to the syspref
336 if ( C4
::Context
->preference('item-level_itypes') ) {
337 unshift @
{ $criteria{'CIRC'} }, 'items.itype';
338 unshift @
{ $criteria{'CAT'} }, 'items.itype';
340 unshift @
{ $criteria{'CIRC'} }, 'biblioitems.itemtype';
341 unshift @
{ $criteria{'CAT'} }, 'biblioitems.itemtype';
345 my $crit = $criteria{$area};
346 my $column_defs = _get_column_defs
($cgi);
348 foreach my $localcrit (@
$crit) {
349 my ( $value, $type ) = split( /\|/, $localcrit );
350 my ( $table, $column ) = split( /\./, $value );
351 if ($type eq 'textrange') {
353 $temp{'name'} = $value;
354 $temp{'from'} = "from_" . $value;
355 $temp{'to'} = "to_" . $value;
356 $temp{'textrange'} = 1;
357 $temp{'description'} = $column_defs->{$value};
358 push @criteria_array, \
%temp;
360 elsif ($type eq 'date') {
362 $temp{'name'} = $value;
364 $temp{'description'} = $column_defs->{$value};
365 push @criteria_array, \
%temp;
367 elsif ($type eq 'daterange') {
369 $temp{'name'} = $value;
370 $temp{'from'} = "from_" . $value;
371 $temp{'to'} = "to_" . $value;
372 $temp{'daterange'} = 1;
373 $temp{'description'} = $column_defs->{$value};
374 push @criteria_array, \
%temp;
378 "SELECT distinct($column) as availablevalues FROM $table";
379 my $sth = $dbh->prepare($query);
382 # push the runtime choosing option
384 $list='branches' if $column eq 'branchcode' or $column eq 'holdingbranch' or $column eq 'homebranch';
385 $list='categorycode' if $column eq 'categorycode';
386 $list='itemtype' if $column eq 'itype';
387 $list='ccode' if $column eq 'ccode';
388 # TODO : improve to let the librarian choose the description at runtime
389 push @values, { availablevalues
=> "<<$column".($list?
"|$list":'').">>" };
390 while ( my $row = $sth->fetchrow_hashref() ) {
392 if ($row->{'availablevalues'} eq '') { $row->{'default'} = 1 };
397 $temp{'name'} = $value;
398 $temp{'description'} = $column_defs->{$value};
399 $temp{'values'} = \
@values;
401 push @criteria_array, \
%temp;
405 return ( \
@criteria_array );
409 my $sql = shift or return;
410 my $sth = C4
::Context
->dbh->prepare($sql);
412 my $rows = $sth->fetchall_arrayref();
413 return scalar (@
$rows);
418 ($sth, $error) = execute_query($sql, $offset, $limit[, \@sql_params])
421 This function returns a DBI statement handler from which the caller can
422 fetch the results of the SQL passed via C<$sql>.
424 If passed any query other than a SELECT, or if there is a DB error,
425 C<$errors> is returned, and is a hashref containing the error after this
428 C<$error->{'sqlerr'}> contains the offending SQL keyword.
429 C<$error->{'queryerr'}> contains the native db engine error returned
432 C<$offset>, and C<$limit> are required parameters.
434 C<\@sql_params> is an optional list of parameter values to paste in.
435 The caller is reponsible for making sure that C<$sql> has placeholders
436 and that the number placeholders matches the number of parameters.
440 # returns $sql, $offset, $limit
441 # $sql returned will be transformed to:
442 # ~ remove any LIMIT clause
443 # ~ repace SELECT clause w/ SELECT count(*)
445 sub select_2_select_count
{
446 # Modify the query passed in to create a count query... (I think this covers all cases -crn)
447 my ($sql) = strip_limit
(shift) or return;
448 $sql =~ s/\bSELECT\W+(?:\w+\W+){1,}?FROM\b|\bSELECT\W\*\WFROM\b/SELECT count(*) FROM /ig;
452 # This removes the LIMIT from the query so that a custom one can be specified.
454 # ($new_sql, $offset, $limit) = strip_limit($sql);
457 # $sql is the query to modify
458 # $new_sql is the resulting query
459 # $offset is the offset value, if the LIMIT was the two-argument form,
460 # 0 if it wasn't otherwise given.
461 # $limit is the limit value
464 # * This makes an effort to not break subqueries that have their own
465 # LIMIT specified. It does that by only removing a LIMIT if it comes after
466 # a WHERE clause (which isn't perfect, but at least should make more cases
467 # work - subqueries with a limit in the WHERE will still break.)
468 # * If your query doesn't have a WHERE clause then all LIMITs will be
469 # removed. This may break some subqueries, but is hopefully rare enough
470 # to not be a big issue.
475 return ($sql, 0, undef) unless $sql =~ /\bLIMIT\b/i;
477 # Two options: if there's no WHERE clause in the SQL, we simply capture
478 # any LIMIT that's there. If there is a WHERE, we make sure that we only
479 # capture a LIMIT after the last one. This prevents stomping on subqueries.
480 if ($sql !~ /\bWHERE\b/i) {
481 (my $res = $sql) =~ s/\bLIMIT\b\s*(\d+)(\s*\,\s*(\d+))?\s*/ /ig;
482 return ($res, (defined $2 ?
$1 : 0), (defined $3 ?
$3 : $1));
485 $res =~ m/.*\bWHERE\b/gsi;
486 $res =~ s/\G(.*)\bLIMIT\b\s*(\d+)(\s*\,\s*(\d+))?\s*/$1 /is;
487 return ($res, (defined $3 ?
$2 : 0), (defined $4 ?
$4 : $2));
493 my ( $sql, $offset, $limit, $sql_params ) = @_;
495 $sql_params = [] unless defined $sql_params;
499 carp
"execute_query() called without SQL argument";
502 $offset = 0 unless $offset;
503 $limit = 999999 unless $limit;
504 $debug and print STDERR
"execute_query($sql, $offset, $limit)\n";
505 if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
506 return (undef, { sqlerr
=> $1} );
507 } elsif ($sql !~ /^\s*SELECT\b\s*/i) {
508 return (undef, { queryerr
=> 'Missing SELECT'} );
511 my ($useroffset, $userlimit);
513 # Grab offset/limit from user supplied LIMIT and drop the LIMIT so we can control pagination
514 ($sql, $useroffset, $userlimit) = strip_limit
($sql);
515 $debug and warn sprintf "User has supplied (OFFSET,) LIMIT = %s, %s",
517 (defined($userlimit ) ?
$userlimit : 'UNDEF');
518 $offset += $useroffset;
519 if (defined($userlimit)) {
520 if ($offset + $limit > $userlimit ) {
521 $limit = $userlimit - $offset;
522 } elsif ( ! $offset && $limit < $userlimit ) {
526 $sql .= " LIMIT ?, ?";
528 my $sth = C4
::Context
->dbh->prepare($sql);
529 $sth->execute(@
$sql_params, $offset, $limit);
530 return ( $sth, { queryerr
=> $sth->errstr } ) if ($sth->err);
532 # my @xmlarray = ... ;
533 # my $url = "/cgi-bin/koha/reports/guided_reports.pl?phase=retrieve%20results&id=$id";
534 # my $xml = XML::Dumper->new()->pl2xml( \@xmlarray );
535 # store_results($id,$xml);
538 =head2 save_report($sql,$name,$type,$notes)
540 Given some sql and a name this will saved it so that it can reused
541 Returns id of the newly created report
547 my $borrowernumber = $fields->{borrowernumber
};
548 my $sql = $fields->{sql
};
549 my $name = $fields->{name
};
550 my $type = $fields->{type
};
551 my $notes = $fields->{notes
};
552 my $area = $fields->{area
};
553 my $group = $fields->{group
};
554 my $subgroup = $fields->{subgroup
};
555 my $cache_expiry = $fields->{cache_expiry
} || 300;
556 my $public = $fields->{public
};
558 my $dbh = C4
::Context
->dbh();
559 $sql =~ s/(\s*\;\s*)$//; # removes trailing whitespace and /;/
560 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(),?,?,?,?,?,?,?,?,?)";
561 $dbh->do($query, undef, $borrowernumber, $sql, $name, $area, $group, $subgroup, $type, $notes, $cache_expiry, $public);
563 my $id = $dbh->selectrow_array("SELECT max(id) FROM saved_sql WHERE borrowernumber=? AND report_name=?", undef,
564 $borrowernumber, $name);
569 my $id = shift || croak
"No Id given";
571 my $sql = $fields->{sql
};
572 my $name = $fields->{name
};
573 my $notes = $fields->{notes
};
574 my $group = $fields->{group
};
575 my $subgroup = $fields->{subgroup
};
576 my $cache_expiry = $fields->{cache_expiry
};
577 my $public = $fields->{public
};
579 if( $cache_expiry >= 2592000 ){
580 die "Please specify a cache expiry less than 30 days\n";
583 my $dbh = C4
::Context
->dbh();
584 $sql =~ s/(\s*\;\s*)$//; # removes trailing whitespace and /;/
585 my $query = "UPDATE saved_sql SET savedsql = ?, last_modified = now(), report_name = ?, report_group = ?, report_subgroup = ?, notes = ?, cache_expiry = ?, public = ? WHERE id = ? ";
586 $dbh->do($query, undef, $sql, $name, $group, $subgroup, $notes, $cache_expiry, $public, $id );
591 my $dbh = C4
::Context
->dbh();
592 my $query = "SELECT * FROM saved_reports WHERE report_id=?";
593 my $sth = $dbh->prepare($query);
595 if (my $data=$sth->fetchrow_hashref()){
596 my $query2 = "UPDATE saved_reports SET report=?,date_run=now() WHERE report_id=?";
597 my $sth2 = $dbh->prepare($query2);
598 $sth2->execute($xml,$id);
601 my $query2 = "INSERT INTO saved_reports (report_id,report,date_run) VALUES (?,?,now())";
602 my $sth2 = $dbh->prepare($query2);
603 $sth2->execute($id,$xml);
609 my $dbh = C4
::Context
->dbh();
610 my $query = "SELECT * FROM saved_reports WHERE report_id = ?";
611 my $sth = $dbh->prepare($query);
613 my $data = $sth->fetchrow_hashref();
614 my $dump = new XML
::Dumper
;
615 my $perl = $dump->xml2pl( $data->{'report'} );
616 foreach my $row (@
$perl) {
618 foreach my $key (keys %$row){
619 $htmlrow .= "<td>$row->{$key}</td>";
622 $row->{'row'} = $htmlrow;
625 $query = "SELECT * FROM saved_sql WHERE id = ?";
626 $sth = $dbh->prepare($query);
628 $data = $sth->fetchrow_hashref();
629 return ($perl,$data->{'report_name'},$data->{'notes'});
635 my $dbh = C4
::Context
->dbh;
636 my $query = 'DELETE FROM saved_sql WHERE id IN (' . join( ',', ('?') x
@ids ) . ')';
637 my $sth = $dbh->prepare($query);
638 return $sth->execute(@ids);
641 sub get_saved_reports_base_query
{
643 my $area_name_sql_snippet = get_area_name_sql_snippet
;
645 SELECT s.*, r.report, r.date_run, $area_name_sql_snippet, av_g.lib AS groupname, av_sg.lib AS subgroupname,
646 b.firstname AS borrowerfirstname, b.surname AS borrowersurname
648 LEFT JOIN saved_reports r ON r.report_id = s.id
649 LEFT OUTER JOIN authorised_values av_g ON (av_g.category = 'REPORT_GROUP' AND av_g.authorised_value = s.report_group)
650 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)
651 LEFT OUTER JOIN borrowers b USING (borrowernumber)
655 sub get_saved_reports
{
656 # $filter is either { date => $d, author => $a, keyword => $kw, }
657 # or $keyword. Optional.
659 $filter = { keyword
=> $filter } if $filter && !ref( $filter );
660 my ($group, $subgroup) = @_;
662 my $dbh = C4
::Context
->dbh();
663 my $query = get_saved_reports_base_query
;
666 if (my $date = $filter->{date
}) {
667 $date = format_date_in_iso
($date);
668 push @cond, "DATE(date_run) = ? OR
669 DATE(date_created) = ? OR
670 DATE(last_modified) = ? OR
672 push @args, $date, $date, $date, $date;
674 if (my $author = $filter->{author
}) {
675 $author = "%$author%";
676 push @cond, "surname LIKE ? OR
678 push @args, $author, $author;
680 if (my $keyword = $filter->{keyword
}) {
683 OR report_name LIKE ?
688 push @args, "%$keyword%", "%$keyword%", "%$keyword%", "%$keyword%", $keyword;
690 if ($filter->{group
}) {
691 push @cond, "report_group = ?";
692 push @args, $filter->{group
};
694 if ($filter->{subgroup
}) {
695 push @cond, "report_subgroup = ?";
696 push @args, $filter->{subgroup
};
699 $query .= " WHERE ".join( " AND ", map "($_)", @cond ) if @cond;
700 $query .= " ORDER by date_created";
702 my $result = $dbh->selectall_arrayref($query, {Slice
=> {}}, @args);
707 sub get_saved_report
{
708 my $dbh = C4
::Context
->dbh();
711 if ($#_ == 0 && ref $_[0] ne 'HASH') {
713 $query = " SELECT * FROM saved_sql WHERE id = ?";
714 } elsif (ref $_[0] eq 'HASH') {
716 if ($selector->{name
}) {
717 $query = " SELECT * FROM saved_sql WHERE report_name = ?";
718 $report_arg = $selector->{name
};
719 } elsif ($selector->{id
} || $selector->{id
} eq '0') {
720 $query = " SELECT * FROM saved_sql WHERE id = ?";
721 $report_arg = $selector->{id
};
728 return $dbh->selectrow_hashref($query, undef, $report_arg);
731 =head2 create_compound($masterID,$subreportID)
733 This will take 2 reports and create a compound report using both of them
737 sub create_compound
{
738 my ( $masterID, $subreportID ) = @_;
739 my $dbh = C4
::Context
->dbh();
742 my $master = get_saved_report
($masterID);
743 my $mastersql = $master->{savedsql
};
744 my $mastertype = $master->{type
};
745 my $sub = get_saved_report
($subreportID);
746 my $subsql = $master->{savedsql
};
747 my $subtype = $master->{type
};
749 # now we have to do some checking to see how these two will fit together
751 my ( $mastertables, $subtables );
752 if ( $mastersql =~ / from (.*) where /i ) {
755 if ( $subsql =~ / from (.*) where /i ) {
758 return ( $mastertables, $subtables );
761 =head2 get_column_type($column)
763 This takes a column name of the format table.column and will return what type it is
764 (free text, set values, date)
768 sub get_column_type
{
769 my ($tablecolumn) = @_;
770 my ($table,$column) = split(/\./,$tablecolumn);
771 my $dbh = C4
::Context
->dbh();
775 # mysql doesnt support a column selection, set column to %
777 my $sth = $dbh->column_info( $catalog, $schema, $table, $tempcolumn ) || die $dbh->errstr;
778 while (my $info = $sth->fetchrow_hashref()){
779 if ($info->{'COLUMN_NAME'} eq $column){
781 if ($info->{'TYPE_NAME'} eq 'CHAR' || $info->{'TYPE_NAME'} eq 'VARCHAR'){
782 $info->{'TYPE_NAME'} = 'distinct';
784 return $info->{'TYPE_NAME'};
789 =head2 get_distinct_values($column)
791 Given a column name, return an arrary ref of hashrefs suitable for use as a tmpl_loop
792 with the distinct values of the column
796 sub get_distinct_values
{
797 my ($tablecolumn) = @_;
798 my ($table,$column) = split(/\./,$tablecolumn);
799 my $dbh = C4
::Context
->dbh();
801 "SELECT distinct($column) as availablevalues FROM $table";
802 my $sth = $dbh->prepare($query);
804 return $sth->fetchall_arrayref({});
807 sub save_dictionary
{
808 my ( $name, $description, $sql, $area ) = @_;
809 my $dbh = C4
::Context
->dbh();
810 my $query = "INSERT INTO reports_dictionary (name,description,saved_sql,report_area,date_created,date_modified)
811 VALUES (?,?,?,?,now(),now())";
812 my $sth = $dbh->prepare($query);
813 $sth->execute($name,$description,$sql,$area) || return 0;
817 sub get_from_dictionary
{
818 my ( $area, $id ) = @_;
819 my $dbh = C4
::Context
->dbh();
820 my $area_name_sql_snippet = get_area_name_sql_snippet
;
822 SELECT d.*, $area_name_sql_snippet
823 FROM reports_dictionary d
827 $query .= " WHERE report_area = ?";
829 $query .= " WHERE id = ?";
831 my $sth = $dbh->prepare($query);
835 $sth->execute($area);
840 while ( my $data = $sth->fetchrow_hashref() ) {
846 sub delete_definition
{
847 my ($id) = @_ or return;
848 my $dbh = C4
::Context
->dbh();
849 my $query = "DELETE FROM reports_dictionary WHERE id = ?";
850 my $sth = $dbh->prepare($query);
855 my ($id) = @_ or return;
856 my $dbh = C4
::Context
->dbh();
857 my $query = "SELECT * FROM saved_sql WHERE id = ?";
858 my $sth = $dbh->prepare($query);
860 my $data=$sth->fetchrow_hashref();
861 return $data->{'savedsql'};
864 sub _get_column_defs
{
867 my $columns_def_file = "columns.def";
868 my $htdocs = C4
::Context
->config('intrahtdocs');
869 my $section = 'intranet';
871 # We need the theme and the lang
872 # Since columns.def is not in the modules directory, we cannot sent it for the $tmpl var
873 my ($theme, $lang, $availablethemes) = C4
::Templates
::themelanguage
($htdocs, 'about.tt', $section, $cgi);
875 my $full_path_to_columns_def_file="$htdocs/$theme/$lang/$columns_def_file";
876 open (my $fh, $full_path_to_columns_def_file);
877 while ( my $input = <$fh> ){
879 if ( $input =~ m
|<field name
="(.*)">(.*)</field
>| ) {
880 my ( $field, $translation ) = ( $1, $2 );
881 $columns{$field} = $translation;
888 =head2 build_authorised_value_list($authorised_value)
890 Returns an arrayref - hashref pair. The hashref consists of
891 various code => name lists depending on the $authorised_value.
892 The arrayref is the hashref keys, in appropriate order
896 sub build_authorised_value_list
{
897 my ( $authorised_value ) = @_;
899 my $dbh = C4
::Context
->dbh;
900 my @authorised_values;
903 # builds list, depending on authorised value...
904 if ( $authorised_value eq "branches" ) {
905 my $branches = GetBranchesLoop
();
906 foreach my $thisbranch (@
$branches) {
907 push @authorised_values, $thisbranch->{value
};
908 $authorised_lib{ $thisbranch->{value
} } = $thisbranch->{branchname
};
910 } elsif ( $authorised_value eq "itemtypes" ) {
911 my $sth = $dbh->prepare("SELECT itemtype,description FROM itemtypes ORDER BY description");
913 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
914 push @authorised_values, $itemtype;
915 $authorised_lib{$itemtype} = $description;
917 } elsif ( $authorised_value eq "cn_source" ) {
918 my $class_sources = GetClassSources
();
919 my $default_source = C4
::Context
->preference("DefaultClassificationSource");
920 foreach my $class_source ( sort keys %$class_sources ) {
922 unless $class_sources->{$class_source}->{'used'}
923 or ( $class_source eq $default_source );
924 push @authorised_values, $class_source;
925 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
927 } elsif ( $authorised_value eq "categorycode" ) {
928 my $sth = $dbh->prepare("SELECT categorycode, description FROM categories ORDER BY description");
930 while ( my ( $categorycode, $description ) = $sth->fetchrow_array ) {
931 push @authorised_values, $categorycode;
932 $authorised_lib{$categorycode} = $description;
935 #---- "true" authorised value
937 my $authorised_values_sth = $dbh->prepare("SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib");
939 $authorised_values_sth->execute($authorised_value);
941 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
942 push @authorised_values, $value;
943 $authorised_lib{$value} = $lib;
945 # For item location, we show the code and the libelle
946 $authorised_lib{$value} = $lib;
950 return (\
@authorised_values, \
%authorised_lib);
953 =head2 GetReservedAuthorisedValues
955 my %reserved_authorised_values = GetReservedAuthorisedValues();
957 Returns a hash containig all reserved words
961 sub GetReservedAuthorisedValues
{
962 my %reserved_authorised_values =
963 map { $_ => 1 } ( 'date',
968 'biblio_framework' );
970 return \
%reserved_authorised_values;
974 =head2 IsAuthorisedValueValid
976 my $is_valid_ath_value = IsAuthorisedValueValid($authorised_value)
978 Returns 1 if $authorised_value is on the reserved authorised values list or
979 in the authorised value categories defined in
983 sub IsAuthorisedValueValid
{
985 my $authorised_value = shift;
986 my $reserved_authorised_values = GetReservedAuthorisedValues
();
988 if ( exists $reserved_authorised_values->{$authorised_value} ||
989 C4
::Koha
::IsAuthorisedValueCategory
($authorised_value) ) {
996 =head2 GetParametersFromSQL
998 my @sql_parameters = GetParametersFromSQL($sql)
1000 Returns an arrayref of hashes containing the keys name and authval
1004 sub GetParametersFromSQL
{
1007 my @split = split(/<<|>>/,$sql);
1008 my @sql_parameters = ();
1010 for ( my $i = 0; $i < ($#split/2) ; $i++ ) {
1011 my ($name,$authval) = split(/\|/,$split[$i*2+1]);
1012 push @sql_parameters, { 'name' => $name, 'authval' => $authval };
1015 return \
@sql_parameters;
1018 =head2 ValidateSQLParameters
1020 my @problematic_parameters = ValidateSQLParameters($sql)
1022 Returns an arrayref of hashes containing the keys name and authval of
1023 those SQL parameters that do not correspond to valid authorised names
1027 sub ValidateSQLParameters
{
1030 my @problematic_parameters = ();
1031 my $sql_parameters = GetParametersFromSQL
($sql);
1033 foreach my $sql_parameter (@
$sql_parameters) {
1034 if ( defined $sql_parameter->{'authval'} ) {
1035 push @problematic_parameters, $sql_parameter unless
1036 IsAuthorisedValueValid
($sql_parameter->{'authval'});
1040 return \
@problematic_parameters;
1048 Chris Cormack <crc@liblime.com>