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::Dates qw/format_date format_date_in_iso/;
27 use C4::Templates qw/themelanguage/;
33 # 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
58 C4::Reports::Guided - Module for generating guided reports
62 use C4::Reports::Guided;
70 =head2 get_report_areas
72 This will return a list of all the available report areas
76 sub get_area_name_sql_snippet
{
78 [CIRC
=> "Circulation"],
81 [ACQ
=> "Acquisition"],
86 return "CASE report_area " .
87 join (" ", map "WHEN '$_->[0]' THEN '$_->[1]'", @REPORT_AREA) .
91 sub get_report_areas
{
93 my $report_areas = [ 'CIRC', 'CAT', 'PAT', 'ACQ', 'ACC', 'SER' ];
100 CIRC
=> [ 'borrowers', 'statistics', 'items', 'biblioitems' ],
101 CAT
=> [ 'items', 'biblioitems', 'biblio' ],
102 PAT
=> ['borrowers'],
103 ACQ
=> [ 'aqorders', 'biblio', 'items' ],
104 ACC
=> [ 'borrowers', 'accountlines' ],
105 SER
=> [ 'serial', 'serialitems', 'subscription', 'subscriptionhistory', 'subscriptionroutinglist', 'biblioitems', 'biblio', 'aqbooksellers' ],
109 =head2 get_report_types
111 This will return a list of all the available report types
115 sub get_report_types
{
116 my $dbh = C4
::Context
->dbh();
118 # FIXME these should be in the database perhaps
119 my @reports = ( 'Tabular', 'Summary', 'Matrix' );
121 for ( my $i = 0 ; $i < 3 ; $i++ ) {
123 $hashrep{id
} = $i + 1;
124 $hashrep{name
} = $reports[$i];
125 push @reports2, \
%hashrep;
127 return ( \
@reports2 );
131 =head2 get_report_groups
133 This will return a list of all the available report areas with groups
137 sub get_report_groups
{
138 my $dbh = C4
::Context
->dbh();
140 my $groups = GetAuthorisedValues
('REPORT_GROUP');
141 my $subgroups = GetAuthorisedValues
('REPORT_SUBGROUP');
143 my %groups_with_subgroups = map { $_->{authorised_value
} => {
147 foreach (@
$subgroups) {
148 my $sg = $_->{authorised_value
};
149 my $g = $_->{lib_opac
}
150 or warn( qq{REPORT_SUBGROUP
"$sg" without REPORT_GROUP
(lib_opac
)} ),
152 my $g_sg = $groups_with_subgroups{$g}
153 or warn( qq{REPORT_SUBGROUP
"$sg" with invalid REPORT_GROUP
"$g"} ),
155 $g_sg->{subgroups
}{$sg} = $_->{lib
};
157 return \
%groups_with_subgroups
160 =head2 get_all_tables
162 This will return a list of all tables in the database
167 my $dbh = C4
::Context
->dbh();
168 my $query = "SHOW TABLES";
169 my $sth = $dbh->prepare($query);
172 while ( my $data = $sth->fetchrow_arrayref() ) {
173 push @tables, $data->[0];
180 =head2 get_columns($area)
182 This will return a list of all columns for a report area
188 # this calls the internal function _get_columns
189 my ( $area, $cgi ) = @_;
190 my %table_areas = get_table_areas
;
191 my $tables = $table_areas{$area}
192 or die qq{Unsuported report area
"$area"};
196 foreach my $table (@
$tables) {
197 my @columns = _get_columns
($table,$cgi, $first);
199 push @allcolumns, @columns;
201 return ( \
@allcolumns );
205 my ($tablename,$cgi, $first) = @_;
206 my $dbh = C4
::Context
->dbh();
207 my $sth = $dbh->prepare("show columns from $tablename");
210 my $column_defs = _get_column_defs
($cgi);
212 $tablehash{'table'}=$tablename;
213 $tablehash{'__first__'} = $first;
214 push @columns, \
%tablehash;
215 while ( my $data = $sth->fetchrow_arrayref() ) {
217 $temphash{'name'} = "$tablename.$data->[0]";
218 $temphash{'description'} = $column_defs->{"$tablename.$data->[0]"};
219 push @columns, \
%temphash;
225 =head2 build_query($columns,$criteria,$orderby,$area)
227 This will build the sql needed to return the results asked for,
228 $columns is expected to be of the format tablename.columnname.
229 This is what get_columns returns.
234 my ( $columns, $criteria, $orderby, $area, $totals, $definition ) = @_;
237 CIRC
=> [ 'statistics.borrowernumber=borrowers.borrowernumber',
238 'items.itemnumber = statistics.itemnumber',
239 'biblioitems.biblioitemnumber = items.biblioitemnumber' ],
240 CAT
=> [ 'items.biblioitemnumber=biblioitems.biblioitemnumber',
241 'biblioitems.biblionumber=biblio.biblionumber' ],
243 ACQ
=> [ 'aqorders.biblionumber=biblio.biblionumber',
244 'biblio.biblionumber=items.biblionumber' ],
245 ACC
=> ['borrowers.borrowernumber=accountlines.borrowernumber'],
246 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'],
251 my $keys = $keys{$area};
252 my %table_areas = get_table_areas
;
253 my $tables = $table_areas{$area};
256 _build_query
( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition );
261 my ( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition) = @_;
263 # $keys is an array of joining constraints
264 my $dbh = C4
::Context
->dbh();
265 my $joinedtables = join( ',', @
$tables );
266 my $joinedcolumns = join( ',', @
$columns );
268 "SELECT $totals $joinedcolumns FROM $tables->[0] ";
269 for (my $i=1;$i<@
$tables;$i++){
270 $query .= "LEFT JOIN $tables->[$i] on ($keys->[$i-1]) ";
274 $criteria =~ s/AND/WHERE/;
275 $query .= " $criteria";
278 my @definitions = split(',',$definition);
280 foreach my $def (@definitions){
281 my $defin=get_from_dictionary
('',$def);
282 $deftext .=" ".$defin->[0]->{'saved_sql'};
284 if ($query =~ /WHERE/i){
288 $deftext =~ s/AND/WHERE/;
294 my @totcolumns = split( ',', $totals );
295 foreach my $total (@totcolumns) {
296 if ( $total =~ /\((.*)\)/ ) {
297 if ( $groupby eq '' ) {
298 $groupby = " GROUP BY $1";
313 =head2 get_criteria($area,$cgi);
315 Returns an arraref to hashrefs suitable for using in a tmpl_loop. With the criteria and available values.
320 my ($area,$cgi) = @_;
321 my $dbh = C4
::Context
->dbh();
323 # have to do someting here to know if its dropdown, free text, date etc
325 CIRC
=> [ 'statistics.type', 'borrowers.categorycode', 'statistics.branch',
326 'biblioitems.publicationyear|date', 'items.dateaccessioned|date' ],
327 CAT
=> [ 'items.itemnumber|textrange', 'items.biblionumber|textrange',
328 'items.barcode|textrange', 'biblio.frameworkcode',
329 'items.holdingbranch', 'items.homebranch',
330 'biblio.datecreated|daterange', 'biblio.timestamp|daterange',
331 'items.onloan|daterange', 'items.ccode',
332 'items.itemcallnumber|textrange', 'items.itype', 'items.itemlost',
334 PAT
=> [ 'borrowers.branchcode', 'borrowers.categorycode' ],
335 ACQ
=> ['aqorders.datereceived|date'],
336 ACC
=> [ 'borrowers.branchcode', 'borrowers.categorycode' ],
337 SER
=> ['subscription.startdate|date', 'subscription.enddate|date', 'subscription.periodicity', 'subscription.callnumber', 'subscription.location', 'subscription.branchcode'],
340 # Adds itemtypes to criteria, according to the syspref
341 if ( C4
::Context
->preference('item-level_itypes') ) {
342 unshift @
{ $criteria{'CIRC'} }, 'items.itype';
343 unshift @
{ $criteria{'CAT'} }, 'items.itype';
345 unshift @
{ $criteria{'CIRC'} }, 'biblioitems.itemtype';
346 unshift @
{ $criteria{'CAT'} }, 'biblioitems.itemtype';
350 my $crit = $criteria{$area};
351 my $column_defs = _get_column_defs
($cgi);
353 foreach my $localcrit (@
$crit) {
354 my ( $value, $type ) = split( /\|/, $localcrit );
355 my ( $table, $column ) = split( /\./, $value );
356 if ($type eq 'textrange') {
358 $temp{'name'} = $value;
359 $temp{'from'} = "from_" . $value;
360 $temp{'to'} = "to_" . $value;
361 $temp{'textrange'} = 1;
362 $temp{'description'} = $column_defs->{$value};
363 push @criteria_array, \
%temp;
365 elsif ($type eq 'date') {
367 $temp{'name'} = $value;
369 $temp{'description'} = $column_defs->{$value};
370 push @criteria_array, \
%temp;
372 elsif ($type eq 'daterange') {
374 $temp{'name'} = $value;
375 $temp{'from'} = "from_" . $value;
376 $temp{'to'} = "to_" . $value;
377 $temp{'daterange'} = 1;
378 $temp{'description'} = $column_defs->{$value};
379 push @criteria_array, \
%temp;
383 "SELECT distinct($column) as availablevalues FROM $table";
384 my $sth = $dbh->prepare($query);
387 # push the runtime choosing option
389 $list='branches' if $column eq 'branchcode' or $column eq 'holdingbranch' or $column eq 'homebranch';
390 $list='categorycode' if $column eq 'categorycode';
391 $list='itemtypes' if $column eq 'itype';
392 $list='ccode' if $column eq 'ccode';
393 # TODO : improve to let the librarian choose the description at runtime
395 availablevalues
=> "<<$column" . ( $list ?
"|$list" : '' ) . ">>",
396 display_value
=> "<<$column" . ( $list ?
"|$list" : '' ) . ">>",
398 while ( my $row = $sth->fetchrow_hashref() ) {
399 if ($row->{'availablevalues'} eq '') { $row->{'default'} = 1 }
400 else { $row->{display_value
} = _get_display_value
( $row->{'availablevalues'}, $column ); }
406 $temp{'name'} = $value;
407 $temp{'description'} = $column_defs->{$value};
408 $temp{'values'} = \
@values;
410 push @criteria_array, \
%temp;
413 return ( \
@criteria_array );
417 my $sql = shift or return;
418 my $sth = C4
::Context
->dbh->prepare($sql);
420 my $rows = $sth->fetchall_arrayref();
421 return scalar (@
$rows);
426 ($sth, $error) = execute_query($sql, $offset, $limit[, \@sql_params])
429 This function returns a DBI statement handler from which the caller can
430 fetch the results of the SQL passed via C<$sql>.
432 If passed any query other than a SELECT, or if there is a DB error,
433 C<$errors> is returned, and is a hashref containing the error after this
436 C<$error->{'sqlerr'}> contains the offending SQL keyword.
437 C<$error->{'queryerr'}> contains the native db engine error returned
440 C<$offset>, and C<$limit> are required parameters.
442 C<\@sql_params> is an optional list of parameter values to paste in.
443 The caller is responsible for making sure that C<$sql> has placeholders
444 and that the number placeholders matches the number of parameters.
448 # returns $sql, $offset, $limit
449 # $sql returned will be transformed to:
450 # ~ remove any LIMIT clause
451 # ~ repace SELECT clause w/ SELECT count(*)
453 sub select_2_select_count
{
454 # Modify the query passed in to create a count query... (I think this covers all cases -crn)
455 my ($sql) = strip_limit
(shift) or return;
456 $sql =~ s/\bSELECT\W+(?:\w+\W+){1,}?FROM\b|\bSELECT\W\*\WFROM\b/SELECT count(*) FROM /ig;
460 # This removes the LIMIT from the query so that a custom one can be specified.
462 # ($new_sql, $offset, $limit) = strip_limit($sql);
465 # $sql is the query to modify
466 # $new_sql is the resulting query
467 # $offset is the offset value, if the LIMIT was the two-argument form,
468 # 0 if it wasn't otherwise given.
469 # $limit is the limit value
472 # * This makes an effort to not break subqueries that have their own
473 # LIMIT specified. It does that by only removing a LIMIT if it comes after
474 # a WHERE clause (which isn't perfect, but at least should make more cases
475 # work - subqueries with a limit in the WHERE will still break.)
476 # * If your query doesn't have a WHERE clause then all LIMITs will be
477 # removed. This may break some subqueries, but is hopefully rare enough
478 # to not be a big issue.
483 return ($sql, 0, undef) unless $sql =~ /\bLIMIT\b/i;
485 # Two options: if there's no WHERE clause in the SQL, we simply capture
486 # any LIMIT that's there. If there is a WHERE, we make sure that we only
487 # capture a LIMIT after the last one. This prevents stomping on subqueries.
488 if ($sql !~ /\bWHERE\b/i) {
489 (my $res = $sql) =~ s/\bLIMIT\b\s*(\d+)(\s*\,\s*(\d+))?\s*/ /ig;
490 return ($res, (defined $2 ?
$1 : 0), (defined $3 ?
$3 : $1));
493 $res =~ m/.*\bWHERE\b/gsi;
494 $res =~ s/\G(.*)\bLIMIT\b\s*(\d+)(\s*\,\s*(\d+))?\s*/$1 /is;
495 return ($res, (defined $3 ?
$2 : 0), (defined $4 ?
$4 : $2));
501 my ( $sql, $offset, $limit, $sql_params ) = @_;
503 $sql_params = [] unless defined $sql_params;
507 carp
"execute_query() called without SQL argument";
510 $offset = 0 unless $offset;
511 $limit = 999999 unless $limit;
512 $debug and print STDERR
"execute_query($sql, $offset, $limit)\n";
513 if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
514 return (undef, { sqlerr
=> $1} );
515 } elsif ($sql !~ /^\s*SELECT\b\s*/i) {
516 return (undef, { queryerr
=> 'Missing SELECT'} );
519 my ($useroffset, $userlimit);
521 # Grab offset/limit from user supplied LIMIT and drop the LIMIT so we can control pagination
522 ($sql, $useroffset, $userlimit) = strip_limit
($sql);
523 $debug and warn sprintf "User has supplied (OFFSET,) LIMIT = %s, %s",
525 (defined($userlimit ) ?
$userlimit : 'UNDEF');
526 $offset += $useroffset;
527 if (defined($userlimit)) {
528 if ($offset + $limit > $userlimit ) {
529 $limit = $userlimit - $offset;
530 } elsif ( ! $offset && $limit < $userlimit ) {
534 $sql .= " LIMIT ?, ?";
536 my $sth = C4
::Context
->dbh->prepare($sql);
537 $sth->execute(@
$sql_params, $offset, $limit);
538 return ( $sth, { queryerr
=> $sth->errstr } ) if ($sth->err);
540 # my @xmlarray = ... ;
541 # my $url = "/cgi-bin/koha/reports/guided_reports.pl?phase=retrieve%20results&id=$id";
542 # my $xml = XML::Dumper->new()->pl2xml( \@xmlarray );
543 # store_results($id,$xml);
546 =head2 save_report($sql,$name,$type,$notes)
548 Given some sql and a name this will saved it so that it can reused
549 Returns id of the newly created report
555 my $borrowernumber = $fields->{borrowernumber
};
556 my $sql = $fields->{sql
};
557 my $name = $fields->{name
};
558 my $type = $fields->{type
};
559 my $notes = $fields->{notes
};
560 my $area = $fields->{area
};
561 my $group = $fields->{group
};
562 my $subgroup = $fields->{subgroup
};
563 my $cache_expiry = $fields->{cache_expiry
} || 300;
564 my $public = $fields->{public
};
566 my $dbh = C4
::Context
->dbh();
567 $sql =~ s/(\s*\;\s*)$//; # removes trailing whitespace and /;/
568 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(),?,?,?,?,?,?,?,?,?)";
569 $dbh->do($query, undef, $borrowernumber, $sql, $name, $area, $group, $subgroup, $type, $notes, $cache_expiry, $public);
571 my $id = $dbh->selectrow_array("SELECT max(id) FROM saved_sql WHERE borrowernumber=? AND report_name=?", undef,
572 $borrowernumber, $name);
577 my $id = shift || croak
"No Id given";
579 my $sql = $fields->{sql
};
580 my $name = $fields->{name
};
581 my $notes = $fields->{notes
};
582 my $group = $fields->{group
};
583 my $subgroup = $fields->{subgroup
};
584 my $cache_expiry = $fields->{cache_expiry
};
585 my $public = $fields->{public
};
587 if( $cache_expiry >= 2592000 ){
588 die "Please specify a cache expiry less than 30 days\n";
591 my $dbh = C4
::Context
->dbh();
592 $sql =~ s/(\s*\;\s*)$//; # removes trailing whitespace and /;/
593 my $query = "UPDATE saved_sql SET savedsql = ?, last_modified = now(), report_name = ?, report_group = ?, report_subgroup = ?, notes = ?, cache_expiry = ?, public = ? WHERE id = ? ";
594 $dbh->do($query, undef, $sql, $name, $group, $subgroup, $notes, $cache_expiry, $public, $id );
599 my $dbh = C4
::Context
->dbh();
600 my $query = "SELECT * FROM saved_reports WHERE report_id=?";
601 my $sth = $dbh->prepare($query);
603 if (my $data=$sth->fetchrow_hashref()){
604 my $query2 = "UPDATE saved_reports SET report=?,date_run=now() WHERE report_id=?";
605 my $sth2 = $dbh->prepare($query2);
606 $sth2->execute($xml,$id);
609 my $query2 = "INSERT INTO saved_reports (report_id,report,date_run) VALUES (?,?,now())";
610 my $sth2 = $dbh->prepare($query2);
611 $sth2->execute($id,$xml);
617 my $dbh = C4
::Context
->dbh();
618 my $query = "SELECT * FROM saved_reports WHERE report_id = ?";
619 my $sth = $dbh->prepare($query);
621 my $data = $sth->fetchrow_hashref();
622 my $dump = new XML
::Dumper
;
623 my $perl = $dump->xml2pl( $data->{'report'} );
624 foreach my $row (@
$perl) {
626 foreach my $key (keys %$row){
627 $htmlrow .= "<td>$row->{$key}</td>";
630 $row->{'row'} = $htmlrow;
633 $query = "SELECT * FROM saved_sql WHERE id = ?";
634 $sth = $dbh->prepare($query);
636 $data = $sth->fetchrow_hashref();
637 return ($perl,$data->{'report_name'},$data->{'notes'});
643 foreach my $id (@ids) {
644 my $data = get_saved_report
($id);
645 logaction
( "REPORTS", "DELETE", $id, "$data->{'report_name'} | $data->{'savedsql'} " ) if C4
::Context
->preference("ReportsLog");
647 my $dbh = C4
::Context
->dbh;
648 my $query = 'DELETE FROM saved_sql WHERE id IN (' . join( ',', ('?') x
@ids ) . ')';
649 my $sth = $dbh->prepare($query);
650 return $sth->execute(@ids);
653 sub get_saved_reports_base_query
{
654 my $area_name_sql_snippet = get_area_name_sql_snippet
;
656 SELECT s.*, r.report, r.date_run, $area_name_sql_snippet, av_g.lib AS groupname, av_sg.lib AS subgroupname,
657 b.firstname AS borrowerfirstname, b.surname AS borrowersurname
659 LEFT JOIN saved_reports r ON r.report_id = s.id
660 LEFT OUTER JOIN authorised_values av_g ON (av_g.category = 'REPORT_GROUP' AND av_g.authorised_value = s.report_group)
661 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)
662 LEFT OUTER JOIN borrowers b USING (borrowernumber)
666 sub get_saved_reports
{
667 # $filter is either { date => $d, author => $a, keyword => $kw, }
668 # or $keyword. Optional.
670 $filter = { keyword
=> $filter } if $filter && !ref( $filter );
671 my ($group, $subgroup) = @_;
673 my $dbh = C4
::Context
->dbh();
674 my $query = get_saved_reports_base_query
;
677 if (my $date = $filter->{date
}) {
678 $date = format_date_in_iso
($date);
679 push @cond, "DATE(date_run) = ? OR
680 DATE(date_created) = ? OR
681 DATE(last_modified) = ? OR
683 push @args, $date, $date, $date, $date;
685 if (my $author = $filter->{author
}) {
686 $author = "%$author%";
687 push @cond, "surname LIKE ? OR
689 push @args, $author, $author;
691 if (my $keyword = $filter->{keyword
}) {
694 OR report_name LIKE ?
699 push @args, "%$keyword%", "%$keyword%", "%$keyword%", "%$keyword%", $keyword;
701 if ($filter->{group
}) {
702 push @cond, "report_group = ?";
703 push @args, $filter->{group
};
705 if ($filter->{subgroup
}) {
706 push @cond, "report_subgroup = ?";
707 push @args, $filter->{subgroup
};
710 $query .= " WHERE ".join( " AND ", map "($_)", @cond ) if @cond;
711 $query .= " ORDER by date_created";
713 my $result = $dbh->selectall_arrayref($query, {Slice
=> {}}, @args);
718 sub get_saved_report
{
719 my $dbh = C4
::Context
->dbh();
722 if ($#_ == 0 && ref $_[0] ne 'HASH') {
724 $query = " SELECT * FROM saved_sql WHERE id = ?";
725 } elsif (ref $_[0] eq 'HASH') {
727 if ($selector->{name
}) {
728 $query = " SELECT * FROM saved_sql WHERE report_name = ?";
729 $report_arg = $selector->{name
};
730 } elsif ($selector->{id
} || $selector->{id
} eq '0') {
731 $query = " SELECT * FROM saved_sql WHERE id = ?";
732 $report_arg = $selector->{id
};
739 return $dbh->selectrow_hashref($query, undef, $report_arg);
742 =head2 create_compound($masterID,$subreportID)
744 This will take 2 reports and create a compound report using both of them
748 sub create_compound
{
749 my ( $masterID, $subreportID ) = @_;
750 my $dbh = C4
::Context
->dbh();
753 my $master = get_saved_report
($masterID);
754 my $mastersql = $master->{savedsql
};
755 my $mastertype = $master->{type
};
756 my $sub = get_saved_report
($subreportID);
757 my $subsql = $master->{savedsql
};
758 my $subtype = $master->{type
};
760 # now we have to do some checking to see how these two will fit together
762 my ( $mastertables, $subtables );
763 if ( $mastersql =~ / from (.*) where /i ) {
766 if ( $subsql =~ / from (.*) where /i ) {
769 return ( $mastertables, $subtables );
772 =head2 get_column_type($column)
774 This takes a column name of the format table.column and will return what type it is
775 (free text, set values, date)
779 sub get_column_type
{
780 my ($tablecolumn) = @_;
781 my ($table,$column) = split(/\./,$tablecolumn);
782 my $dbh = C4
::Context
->dbh();
786 # mysql doesn't support a column selection, set column to %
788 my $sth = $dbh->column_info( $catalog, $schema, $table, $tempcolumn ) || die $dbh->errstr;
789 while (my $info = $sth->fetchrow_hashref()){
790 if ($info->{'COLUMN_NAME'} eq $column){
792 if ($info->{'TYPE_NAME'} eq 'CHAR' || $info->{'TYPE_NAME'} eq 'VARCHAR'){
793 $info->{'TYPE_NAME'} = 'distinct';
795 return $info->{'TYPE_NAME'};
800 =head2 get_distinct_values($column)
802 Given a column name, return an arrary ref of hashrefs suitable for use as a tmpl_loop
803 with the distinct values of the column
807 sub get_distinct_values
{
808 my ($tablecolumn) = @_;
809 my ($table,$column) = split(/\./,$tablecolumn);
810 my $dbh = C4
::Context
->dbh();
812 "SELECT distinct($column) as availablevalues FROM $table";
813 my $sth = $dbh->prepare($query);
815 return $sth->fetchall_arrayref({});
818 sub save_dictionary
{
819 my ( $name, $description, $sql, $area ) = @_;
820 my $dbh = C4
::Context
->dbh();
821 my $query = "INSERT INTO reports_dictionary (name,description,saved_sql,report_area,date_created,date_modified)
822 VALUES (?,?,?,?,now(),now())";
823 my $sth = $dbh->prepare($query);
824 $sth->execute($name,$description,$sql,$area) || return 0;
828 sub get_from_dictionary
{
829 my ( $area, $id ) = @_;
830 my $dbh = C4
::Context
->dbh();
831 my $area_name_sql_snippet = get_area_name_sql_snippet
;
833 SELECT d.*, $area_name_sql_snippet
834 FROM reports_dictionary d
838 $query .= " WHERE report_area = ?";
840 $query .= " WHERE id = ?";
842 my $sth = $dbh->prepare($query);
846 $sth->execute($area);
851 while ( my $data = $sth->fetchrow_hashref() ) {
857 sub delete_definition
{
858 my ($id) = @_ or return;
859 my $dbh = C4
::Context
->dbh();
860 my $query = "DELETE FROM reports_dictionary WHERE id = ?";
861 my $sth = $dbh->prepare($query);
866 my ($id) = @_ or return;
867 my $dbh = C4
::Context
->dbh();
868 my $query = "SELECT * FROM saved_sql WHERE id = ?";
869 my $sth = $dbh->prepare($query);
871 my $data=$sth->fetchrow_hashref();
872 return $data->{'savedsql'};
875 sub _get_column_defs
{
878 my $columns_def_file = "columns.def";
879 my $htdocs = C4
::Context
->config('intrahtdocs');
880 my $section = 'intranet';
882 # We need the theme and the lang
883 # Since columns.def is not in the modules directory, we cannot sent it for the $tmpl var
884 my ($theme, $lang, $availablethemes) = C4
::Templates
::themelanguage
($htdocs, 'about.tt', $section, $cgi);
886 my $full_path_to_columns_def_file="$htdocs/$theme/$lang/$columns_def_file";
887 open (my $fh, $full_path_to_columns_def_file);
888 while ( my $input = <$fh> ){
890 if ( $input =~ m
|<field name
="(.*)">(.*)</field
>| ) {
891 my ( $field, $translation ) = ( $1, $2 );
892 $columns{$field} = $translation;
899 =head2 build_authorised_value_list($authorised_value)
901 Returns an arrayref - hashref pair. The hashref consists of
902 various code => name lists depending on the $authorised_value.
903 The arrayref is the hashref keys, in appropriate order
907 sub build_authorised_value_list
{
908 my ( $authorised_value ) = @_;
910 my $dbh = C4
::Context
->dbh;
911 my @authorised_values;
914 # builds list, depending on authorised value...
915 if ( $authorised_value eq "branches" ) {
916 my $branches = GetBranchesLoop
();
917 foreach my $thisbranch (@
$branches) {
918 push @authorised_values, $thisbranch->{value
};
919 $authorised_lib{ $thisbranch->{value
} } = $thisbranch->{branchname
};
921 } elsif ( $authorised_value eq "itemtypes" ) {
922 my $sth = $dbh->prepare("SELECT itemtype,description FROM itemtypes ORDER BY description");
924 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
925 push @authorised_values, $itemtype;
926 $authorised_lib{$itemtype} = $description;
928 } elsif ( $authorised_value eq "cn_source" ) {
929 my $class_sources = GetClassSources
();
930 my $default_source = C4
::Context
->preference("DefaultClassificationSource");
931 foreach my $class_source ( sort keys %$class_sources ) {
933 unless $class_sources->{$class_source}->{'used'}
934 or ( $class_source eq $default_source );
935 push @authorised_values, $class_source;
936 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
938 } elsif ( $authorised_value eq "categorycode" ) {
939 my $sth = $dbh->prepare("SELECT categorycode, description FROM categories ORDER BY description");
941 while ( my ( $categorycode, $description ) = $sth->fetchrow_array ) {
942 push @authorised_values, $categorycode;
943 $authorised_lib{$categorycode} = $description;
946 #---- "true" authorised value
948 my $authorised_values_sth = $dbh->prepare("SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib");
950 $authorised_values_sth->execute($authorised_value);
952 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
953 push @authorised_values, $value;
954 $authorised_lib{$value} = $lib;
956 # For item location, we show the code and the libelle
957 $authorised_lib{$value} = $lib;
961 return (\
@authorised_values, \
%authorised_lib);
964 =head2 GetReservedAuthorisedValues
966 my %reserved_authorised_values = GetReservedAuthorisedValues();
968 Returns a hash containig all reserved words
972 sub GetReservedAuthorisedValues
{
973 my %reserved_authorised_values =
974 map { $_ => 1 } ( 'date',
979 'biblio_framework' );
981 return \
%reserved_authorised_values;
985 =head2 IsAuthorisedValueValid
987 my $is_valid_ath_value = IsAuthorisedValueValid($authorised_value)
989 Returns 1 if $authorised_value is on the reserved authorised values list or
990 in the authorised value categories defined in
994 sub IsAuthorisedValueValid
{
996 my $authorised_value = shift;
997 my $reserved_authorised_values = GetReservedAuthorisedValues
();
999 if ( exists $reserved_authorised_values->{$authorised_value} ||
1000 C4
::Koha
::IsAuthorisedValueCategory
($authorised_value) ) {
1007 =head2 GetParametersFromSQL
1009 my @sql_parameters = GetParametersFromSQL($sql)
1011 Returns an arrayref of hashes containing the keys name and authval
1015 sub GetParametersFromSQL
{
1018 my @split = split(/<<|>>/,$sql);
1019 my @sql_parameters = ();
1021 for ( my $i = 0; $i < ($#split/2) ; $i++ ) {
1022 my ($name,$authval) = split(/\|/,$split[$i*2+1]);
1023 push @sql_parameters, { 'name' => $name, 'authval' => $authval };
1026 return \
@sql_parameters;
1029 =head2 ValidateSQLParameters
1031 my @problematic_parameters = ValidateSQLParameters($sql)
1033 Returns an arrayref of hashes containing the keys name and authval of
1034 those SQL parameters that do not correspond to valid authorised names
1038 sub ValidateSQLParameters
{
1041 my @problematic_parameters = ();
1042 my $sql_parameters = GetParametersFromSQL
($sql);
1044 foreach my $sql_parameter (@
$sql_parameters) {
1045 if ( defined $sql_parameter->{'authval'} ) {
1046 push @problematic_parameters, $sql_parameter unless
1047 IsAuthorisedValueValid
($sql_parameter->{'authval'});
1051 return \
@problematic_parameters;
1054 sub _get_display_value
{
1055 my ( $original_value, $column ) = @_;
1056 if ( $column eq 'periodicity' ) {
1057 my $dbh = C4
::Context
->dbh();
1058 my $query = "SELECT description FROM subscription_frequencies WHERE id = ?";
1059 my $sth = $dbh->prepare($query);
1060 $sth->execute($original_value);
1061 return $sth->fetchrow;
1063 return $original_value;
1071 Chris Cormack <crc@liblime.com>