Bug 21066: Update NewsChannels.t
[koha.git] / C4 / Reports / Guided.pm
1 package C4::Reports::Guided;
2
3 # Copyright 2007 Liblime Ltd
4 #
5 # This file is part of Koha.
6 #
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.
11 #
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.
16 #
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>.
19
20 use Modern::Perl;
21 use CGI qw ( -utf8 );
22 use Carp;
23 use JSON qw( from_json );
24
25 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
26 use C4::Context;
27 use C4::Templates qw/themelanguage/;
28 use C4::Koha;
29 use Koha::DateUtils;
30 use Koha::Patrons;
31 use Koha::Reports;
32 use C4::Output;
33 use C4::Debug;
34 use C4::Log;
35 use Koha::Notice::Templates;
36 use C4::Letters;
37
38 use Koha::AuthorisedValues;
39 use Koha::Patron::Categories;
40 use Koha::SharedContent;
41
42 BEGIN {
43     require Exporter;
44     @ISA    = qw(Exporter);
45     @EXPORT = qw(
46       get_report_types get_report_areas get_report_groups get_columns build_query get_criteria
47       save_report get_saved_reports execute_query
48       get_column_type get_distinct_values save_dictionary get_from_dictionary
49       delete_definition delete_report format_results get_sql
50       nb_rows update_sql
51       GetReservedAuthorisedValues
52       GetParametersFromSQL
53       IsAuthorisedValueValid
54       ValidateSQLParameters
55       nb_rows update_sql
56     );
57 }
58
59 =head1 NAME
60
61 C4::Reports::Guided - Module for generating guided reports 
62
63 =head1 SYNOPSIS
64
65   use C4::Reports::Guided;
66
67 =head1 DESCRIPTION
68
69 =cut
70
71 =head1 METHODS
72
73 =head2 get_report_areas
74
75 This will return a list of all the available report areas
76
77 =cut
78
79 sub get_area_name_sql_snippet {
80     my @REPORT_AREA = (
81         [CIRC => "Circulation"],
82         [CAT  => "Catalogue"],
83         [PAT  => "Patrons"],
84         [ACQ  => "Acquisition"],
85         [ACC  => "Accounts"],
86         [SER  => "Serials"],
87     );
88
89     return "CASE report_area " .
90     join (" ", map "WHEN '$_->[0]' THEN '$_->[1]'", @REPORT_AREA) .
91     " END AS areaname";
92 }
93
94 sub get_report_areas {
95
96     my $report_areas = [ 'CIRC', 'CAT', 'PAT', 'ACQ', 'ACC', 'SER' ];
97
98     return $report_areas;
99 }
100
101 sub get_table_areas {
102     return (
103     CIRC => [ 'borrowers', 'statistics', 'items', 'biblioitems' ],
104     CAT  => [ 'items', 'biblioitems', 'biblio' ],
105     PAT  => ['borrowers'],
106     ACQ  => [ 'aqorders', 'biblio', 'items' ],
107     ACC  => [ 'borrowers', 'accountlines' ],
108     SER  => [ 'serial', 'serialitems', 'subscription', 'subscriptionhistory', 'subscriptionroutinglist', 'biblioitems', 'biblio', 'aqbooksellers' ],
109     );
110 }
111
112 =head2 get_report_types
113
114 This will return a list of all the available report types
115
116 =cut
117
118 sub get_report_types {
119     my $dbh = C4::Context->dbh();
120
121     # FIXME these should be in the database perhaps
122     my @reports = ( 'Tabular', 'Summary', 'Matrix' );
123     my @reports2;
124     for ( my $i = 0 ; $i < 3 ; $i++ ) {
125         my %hashrep;
126         $hashrep{id}   = $i + 1;
127         $hashrep{name} = $reports[$i];
128         push @reports2, \%hashrep;
129     }
130     return ( \@reports2 );
131
132 }
133
134 =head2 get_report_groups
135
136 This will return a list of all the available report areas with groups
137
138 =cut
139
140 sub get_report_groups {
141     my $dbh = C4::Context->dbh();
142
143     my $groups = GetAuthorisedValues('REPORT_GROUP');
144     my $subgroups = GetAuthorisedValues('REPORT_SUBGROUP');
145
146     my %groups_with_subgroups = map { $_->{authorised_value} => {
147                         name => $_->{lib},
148                         groups => {}
149                     } } @$groups;
150     foreach (@$subgroups) {
151         my $sg = $_->{authorised_value};
152         my $g = $_->{lib_opac}
153           or warn( qq{REPORT_SUBGROUP "$sg" without REPORT_GROUP (lib_opac)} ),
154              next;
155         my $g_sg = $groups_with_subgroups{$g}
156           or warn( qq{REPORT_SUBGROUP "$sg" with invalid REPORT_GROUP "$g"} ),
157              next;
158         $g_sg->{subgroups}{$sg} = $_->{lib};
159     }
160     return \%groups_with_subgroups
161 }
162
163 =head2 get_all_tables
164
165 This will return a list of all tables in the database 
166
167 =cut
168
169 sub get_all_tables {
170     my $dbh   = C4::Context->dbh();
171     my $query = "SHOW TABLES";
172     my $sth   = $dbh->prepare($query);
173     $sth->execute();
174     my @tables;
175     while ( my $data = $sth->fetchrow_arrayref() ) {
176         push @tables, $data->[0];
177     }
178     $sth->finish();
179     return ( \@tables );
180
181 }
182
183 =head2 get_columns($area)
184
185 This will return a list of all columns for a report area
186
187 =cut
188
189 sub get_columns {
190
191     # this calls the internal function _get_columns
192     my ( $area, $cgi ) = @_;
193     my %table_areas = get_table_areas;
194     my $tables = $table_areas{$area}
195       or die qq{Unsuported report area "$area"};
196
197     my @allcolumns;
198     my $first = 1;
199     foreach my $table (@$tables) {
200         my @columns = _get_columns($table,$cgi, $first);
201         $first = 0;
202         push @allcolumns, @columns;
203     }
204     return ( \@allcolumns );
205 }
206
207 sub _get_columns {
208     my ($tablename,$cgi, $first) = @_;
209     my $dbh         = C4::Context->dbh();
210     my $sth         = $dbh->prepare("show columns from $tablename");
211     $sth->execute();
212     my @columns;
213         my $column_defs = _get_column_defs($cgi);
214         my %tablehash;
215         $tablehash{'table'}=$tablename;
216     $tablehash{'__first__'} = $first;
217         push @columns, \%tablehash;
218     while ( my $data = $sth->fetchrow_arrayref() ) {
219         my %temphash;
220         $temphash{'name'}        = "$tablename.$data->[0]";
221         $temphash{'description'} = $column_defs->{"$tablename.$data->[0]"};
222         push @columns, \%temphash;
223     }
224     $sth->finish();
225     return (@columns);
226 }
227
228 =head2 build_query($columns,$criteria,$orderby,$area)
229
230 This will build the sql needed to return the results asked for, 
231 $columns is expected to be of the format tablename.columnname.
232 This is what get_columns returns.
233
234 =cut
235
236 sub build_query {
237     my ( $columns, $criteria, $orderby, $area, $totals, $definition ) = @_;
238
239     my %keys = (
240         CIRC => [ 'statistics.borrowernumber=borrowers.borrowernumber',
241                   'items.itemnumber = statistics.itemnumber',
242                   'biblioitems.biblioitemnumber = items.biblioitemnumber' ],
243         CAT  => [ 'items.biblioitemnumber=biblioitems.biblioitemnumber',
244                   'biblioitems.biblionumber=biblio.biblionumber' ],
245         PAT  => [],
246         ACQ  => [ 'aqorders.biblionumber=biblio.biblionumber',
247                   'biblio.biblionumber=items.biblionumber' ],
248         ACC  => ['borrowers.borrowernumber=accountlines.borrowernumber'],
249         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'],
250     );
251
252
253 ### $orderby
254     my $keys   = $keys{$area};
255     my %table_areas = get_table_areas;
256     my $tables = $table_areas{$area};
257
258     my $sql =
259       _build_query( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition );
260     return ($sql);
261 }
262
263 sub _build_query {
264     my ( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition) = @_;
265 ### $orderby
266     # $keys is an array of joining constraints
267     my $dbh           = C4::Context->dbh();
268     my $joinedtables  = join( ',', @$tables );
269     my $joinedcolumns = join( ',', @$columns );
270     my $query =
271       "SELECT $totals $joinedcolumns FROM $tables->[0] ";
272         for (my $i=1;$i<@$tables;$i++){
273                 $query .= "LEFT JOIN $tables->[$i] on ($keys->[$i-1]) ";
274         }
275
276     if ($criteria) {
277                 $criteria =~ s/AND/WHERE/;
278         $query .= " $criteria";
279     }
280         if ($definition){
281                 my @definitions = split(',',$definition);
282                 my $deftext;
283                 foreach my $def (@definitions){
284                         my $defin=get_from_dictionary('',$def);
285                         $deftext .=" ".$defin->[0]->{'saved_sql'};
286                 }
287                 if ($query =~ /WHERE/i){
288                         $query .= $deftext;
289                 }
290                 else {
291                         $deftext  =~ s/AND/WHERE/;
292                         $query .= $deftext;                     
293                 }
294         }
295     if ($totals) {
296         my $groupby;
297         my @totcolumns = split( ',', $totals );
298         foreach my $total (@totcolumns) {
299             if ( $total =~ /\((.*)\)/ ) {
300                 if ( $groupby eq '' ) {
301                     $groupby = " GROUP BY $1";
302                 }
303                 else {
304                     $groupby .= ",$1";
305                 }
306             }
307         }
308         $query .= $groupby;
309     }
310     if ($orderby) {
311         $query .= $orderby;
312     }
313     return ($query);
314 }
315
316 =head2 get_criteria($area,$cgi);
317
318 Returns an arraref to hashrefs suitable for using in a tmpl_loop. With the criteria and available values.
319
320 =cut
321
322 sub get_criteria {
323     my ($area,$cgi) = @_;
324     my $dbh    = C4::Context->dbh();
325
326     # have to do someting here to know if its dropdown, free text, date etc
327     my %criteria = (
328         CIRC => [ 'statistics.type', 'borrowers.categorycode', 'statistics.branch',
329                   'biblioitems.publicationyear|date', 'items.dateaccessioned|date' ],
330         CAT  => [ 'items.itemnumber|textrange', 'items.biblionumber|textrange',
331                   'items.barcode|textrange', 'biblio.frameworkcode',
332                   'items.holdingbranch', 'items.homebranch',
333                   'biblio.datecreated|daterange', 'biblio.timestamp|daterange',
334                   'items.onloan|daterange', 'items.ccode',
335                   'items.itemcallnumber|textrange', 'items.itype', 'items.itemlost',
336                   'items.location' ],
337         PAT  => [ 'borrowers.branchcode', 'borrowers.categorycode' ],
338         ACQ  => ['aqorders.datereceived|date'],
339         ACC  => [ 'borrowers.branchcode', 'borrowers.categorycode' ],
340         SER  => ['subscription.startdate|date', 'subscription.enddate|date', 'subscription.periodicity', 'subscription.callnumber', 'subscription.location', 'subscription.branchcode'],
341     );
342
343     # Adds itemtypes to criteria, according to the syspref
344     if ( C4::Context->preference('item-level_itypes') ) {
345         unshift @{ $criteria{'CIRC'} }, 'items.itype';
346         unshift @{ $criteria{'CAT'} }, 'items.itype';
347     } else {
348         unshift @{ $criteria{'CIRC'} }, 'biblioitems.itemtype';
349         unshift @{ $criteria{'CAT'} }, 'biblioitems.itemtype';
350     }
351
352
353     my $crit   = $criteria{$area};
354     my $column_defs = _get_column_defs($cgi);
355     my @criteria_array;
356     foreach my $localcrit (@$crit) {
357         my ( $value, $type )   = split( /\|/, $localcrit );
358         my ( $table, $column ) = split( /\./, $value );
359         if ($type eq 'textrange') {
360             my %temp;
361             $temp{'name'}        = $value;
362             $temp{'from'}        = "from_" . $value;
363             $temp{'to'}          = "to_" . $value;
364             $temp{'textrange'}   = 1;
365             $temp{'description'} = $column_defs->{$value};
366             push @criteria_array, \%temp;
367         }
368         elsif ($type eq 'date') {
369             my %temp;
370             $temp{'name'}        = $value;
371             $temp{'date'}        = 1;
372             $temp{'description'} = $column_defs->{$value};
373             push @criteria_array, \%temp;
374         }
375         elsif ($type eq 'daterange') {
376             my %temp;
377             $temp{'name'}        = $value;
378             $temp{'from'}        = "from_" . $value;
379             $temp{'to'}          = "to_" . $value;
380             $temp{'daterange'}   = 1;
381             $temp{'description'} = $column_defs->{$value};
382             push @criteria_array, \%temp;
383         }
384         else {
385             my $query =
386             "SELECT distinct($column) as availablevalues FROM $table";
387             my $sth = $dbh->prepare($query);
388             $sth->execute();
389             my @values;
390             # push the runtime choosing option
391             my $list;
392             $list='branches' if $column eq 'branchcode' or $column eq 'holdingbranch' or $column eq 'homebranch';
393             $list='categorycode' if $column eq 'categorycode';
394             $list='itemtypes' if $column eq 'itype';
395             $list='ccode' if $column eq 'ccode';
396             # TODO : improve to let the librarian choose the description at runtime
397             push @values, {
398                 availablevalues => "<<$column" . ( $list ? "|$list" : '' ) . ">>",
399                 display_value   => "<<$column" . ( $list ? "|$list" : '' ) . ">>",
400             };
401             while ( my $row = $sth->fetchrow_hashref() ) {
402                 if ($row->{'availablevalues'} eq '') { $row->{'default'} = 1 }
403                 else { $row->{display_value} = _get_display_value( $row->{'availablevalues'}, $column ); }
404                 push @values, $row;
405             }
406             $sth->finish();
407
408             my %temp;
409             $temp{'name'}        = $value;
410             $temp{'description'} = $column_defs->{$value};
411             $temp{'values'}      = \@values;
412
413             push @criteria_array, \%temp;
414         }
415     }
416     return ( \@criteria_array );
417 }
418
419 sub nb_rows {
420     my $sql = shift or return;
421
422     my $derived_name = 'xxx';
423     # make sure the derived table name is not already used
424     while ( $sql =~ m/$derived_name/ ) {
425         $derived_name .= 'x';
426     }
427
428
429     my $dbh = C4::Context->dbh;
430     my $sth;
431     my $n = 0;
432
433     my $RaiseError = $dbh->{RaiseError};
434     my $PrintError = $dbh->{PrintError};
435     $dbh->{RaiseError} = 1;
436     $dbh->{PrintError} = 0;
437     eval {
438         $sth = $dbh->prepare(qq{
439             SELECT COUNT(*) FROM
440             ( $sql ) $derived_name
441         });
442
443         $sth->execute();
444     };
445     $dbh->{RaiseError} = $RaiseError;
446     $dbh->{PrintError} = $PrintError;
447     if ($@) { # To catch "Duplicate column name" caused by the derived table, or any other syntax error
448         eval {
449             $sth = $dbh->prepare($sql);
450             $sth->execute;
451         };
452         warn $@ if $@;
453         # Loop through the complete results, fetching 1,000 rows at a time.  This
454         # lowers memory requirements but increases execution time.
455         while (my $rows = $sth->fetchall_arrayref(undef, 1000)) {
456             $n += @$rows;
457         }
458         return $n;
459     }
460
461     my $results = $sth->fetch;
462     return $results ? $results->[0] : 0;
463 }
464
465 =head2 execute_query
466
467   ($sth, $error) = execute_query($sql, $offset, $limit[, \@sql_params])
468
469
470 This function returns a DBI statement handler from which the caller can
471 fetch the results of the SQL passed via C<$sql>.
472
473 If passed any query other than a SELECT, or if there is a DB error,
474 C<$errors> is returned, and is a hashref containing the error after this
475 manner:
476
477 C<$error->{'sqlerr'}> contains the offending SQL keyword.
478 C<$error->{'queryerr'}> contains the native db engine error returned
479 for the query.
480
481 C<$offset>, and C<$limit> are required parameters.
482
483 C<\@sql_params> is an optional list of parameter values to paste in.
484 The caller is responsible for making sure that C<$sql> has placeholders
485 and that the number placeholders matches the number of parameters.
486
487 =cut
488
489 # returns $sql, $offset, $limit
490 # $sql returned will be transformed to:
491 #  ~ remove any LIMIT clause
492 #  ~ repace SELECT clause w/ SELECT count(*)
493
494 sub select_2_select_count {
495     # Modify the query passed in to create a count query... (I think this covers all cases -crn)
496     my ($sql) = strip_limit(shift) or return;
497     $sql =~ s/\bSELECT\W+(?:\w+\W+){1,}?FROM\b|\bSELECT\W\*\WFROM\b/SELECT count(*) FROM /ig;
498     return $sql;
499 }
500
501 # This removes the LIMIT from the query so that a custom one can be specified.
502 # Usage:
503 #   ($new_sql, $offset, $limit) = strip_limit($sql);
504 #
505 # Where:
506 #   $sql is the query to modify
507 #   $new_sql is the resulting query
508 #   $offset is the offset value, if the LIMIT was the two-argument form,
509 #       0 if it wasn't otherwise given.
510 #   $limit is the limit value
511 #
512 # Notes:
513 #   * This makes an effort to not break subqueries that have their own
514 #     LIMIT specified. It does that by only removing a LIMIT if it comes after
515 #     a WHERE clause (which isn't perfect, but at least should make more cases
516 #     work - subqueries with a limit in the WHERE will still break.)
517 #   * If your query doesn't have a WHERE clause then all LIMITs will be
518 #     removed. This may break some subqueries, but is hopefully rare enough
519 #     to not be a big issue.
520 sub strip_limit {
521     my ($sql) = @_;
522
523     return unless $sql;
524     return ($sql, 0, undef) unless $sql =~ /\bLIMIT\b/i;
525
526     # Two options: if there's no WHERE clause in the SQL, we simply capture
527     # any LIMIT that's there. If there is a WHERE, we make sure that we only
528     # capture a LIMIT after the last one. This prevents stomping on subqueries.
529     if ($sql !~ /\bWHERE\b/i) {
530         (my $res = $sql) =~ s/\bLIMIT\b\s*(\d+)(\s*\,\s*(\d+))?\s*/ /ig;
531         return ($res, (defined $2 ? $1 : 0), (defined $3 ? $3 : $1));
532     } else {
533         my $res = $sql;
534         $res =~ m/.*\bWHERE\b/gsi;
535         $res =~ s/\G(.*)\bLIMIT\b\s*(\d+)(\s*\,\s*(\d+))?\s*/$1 /is;
536         return ($res, (defined $3 ? $2 : 0), (defined $4 ? $4 : $2));
537     }
538 }
539
540 sub execute_query {
541
542     my ( $sql, $offset, $limit, $sql_params, $report_id ) = @_;
543
544     $sql_params = [] unless defined $sql_params;
545
546     # check parameters
547     unless ($sql) {
548         carp "execute_query() called without SQL argument";
549         return;
550     }
551     $offset = 0    unless $offset;
552     $limit  = 999999 unless $limit;
553     $debug and print STDERR "execute_query($sql, $offset, $limit)\n";
554     if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
555         return (undef, {  sqlerr => $1} );
556     } elsif ($sql !~ /^\s*SELECT\b\s*/i) {
557         return (undef, { queryerr => 'Missing SELECT'} );
558     }
559
560     my ($useroffset, $userlimit);
561
562     # Grab offset/limit from user supplied LIMIT and drop the LIMIT so we can control pagination
563     ($sql, $useroffset, $userlimit) = strip_limit($sql);
564     $debug and warn sprintf "User has supplied (OFFSET,) LIMIT = %s, %s",
565         $useroffset,
566         (defined($userlimit ) ? $userlimit  : 'UNDEF');
567     $offset += $useroffset;
568     if (defined($userlimit)) {
569         if ($offset + $limit > $userlimit ) {
570             $limit = $userlimit - $offset;
571         } elsif ( ! $offset && $limit < $userlimit ) {
572             $limit = $userlimit;
573         }
574     }
575     $sql .= " LIMIT ?, ?";
576
577     my $dbh = C4::Context->dbh;
578
579     $dbh->do( 'UPDATE saved_sql SET last_run = NOW() WHERE id = ?', undef, $report_id ) if $report_id;
580
581     my $sth = $dbh->prepare($sql);
582     eval {
583         $sth->execute(@$sql_params, $offset, $limit);
584     };
585     warn $@ if $@;
586
587     return ( $sth, { queryerr => $sth->errstr } ) if ($sth->err);
588     return ( $sth );
589 }
590
591 =head2 save_report($sql,$name,$type,$notes)
592
593 Given some sql and a name this will saved it so that it can reused
594 Returns id of the newly created report
595
596 =cut
597
598 sub save_report {
599     my ($fields) = @_;
600     my $borrowernumber = $fields->{borrowernumber};
601     my $sql = $fields->{sql};
602     my $name = $fields->{name};
603     my $type = $fields->{type};
604     my $notes = $fields->{notes};
605     my $area = $fields->{area};
606     my $group = $fields->{group};
607     my $subgroup = $fields->{subgroup};
608     my $cache_expiry = $fields->{cache_expiry};
609     my $public = $fields->{public};
610
611     $sql =~ s/(\s*\;\s*)$//;    # removes trailing whitespace and /;/
612     my $now = dt_from_string;
613     my $report = Koha::Report->new(
614         {
615             borrowernumber  => $borrowernumber,
616             date_created    => $now, # Must be moved to Koha::Report->store
617             last_modified   => $now, # Must be moved to Koha::Report->store
618             savedsql        => $sql,
619             report_name     => $name,
620             report_area     => $area,
621             report_group    => $group,
622             report_subgroup => $subgroup,
623             type            => $type,
624             notes           => $notes,
625             cache_expiry    => $cache_expiry,
626             public          => $public,
627         }
628     )->store;
629
630     return $report->id;
631 }
632
633 sub update_sql {
634     my $id         = shift || croak "No Id given";
635     my $fields     = shift;
636     my $sql = $fields->{sql};
637     my $name = $fields->{name};
638     my $notes = $fields->{notes};
639     my $group = $fields->{group};
640     my $subgroup = $fields->{subgroup};
641     my $cache_expiry = $fields->{cache_expiry};
642     my $public = $fields->{public};
643
644     $sql =~ s/(\s*\;\s*)$//;    # removes trailing whitespace and /;/
645     my $report = Koha::Reports->find($id);
646     $report->last_modified(dt_from_string);
647     $report->savedsql($sql);
648     $report->report_name($name);
649     $report->notes($notes);
650     $report->report_group($group);
651     $report->report_subgroup($subgroup);
652     $report->cache_expiry($cache_expiry) if defined $cache_expiry;
653     $report->public($public);
654     $report->store();
655     if( $cache_expiry >= 2592000 ){
656       die "Please specify a cache expiry less than 30 days\n"; # That's a bit harsh
657     }
658
659     return $report;
660 }
661
662 sub store_results {
663     my ( $id, $json ) = @_;
664     my $dbh = C4::Context->dbh();
665     $dbh->do(q|
666         INSERT INTO saved_reports ( report_id, report, date_run ) VALUES ( ?, ?, NOW() );
667     |, undef, $id, $json );
668 }
669
670 sub format_results {
671     my ( $id ) = @_;
672     my $dbh = C4::Context->dbh();
673     my ( $report_name, $notes, $json, $date_run ) = $dbh->selectrow_array(q|
674        SELECT ss.report_name, ss.notes, sr.report, sr.date_run
675        FROM saved_sql ss
676        LEFT JOIN saved_reports sr ON sr.report_id = ss.id
677        WHERE sr.id = ?
678     |, undef, $id);
679     return {
680         report_name => $report_name,
681         notes => $notes,
682         results => from_json( $json ),
683         date_run => $date_run,
684     };
685 }
686
687 sub delete_report {
688     my (@ids) = @_;
689     return unless @ids;
690     foreach my $id (@ids) {
691         my $data = Koha::Reports->find($id);
692         logaction( "REPORTS", "DELETE", $id, $data->report_name." | ".$data->savedsql ) if C4::Context->preference("ReportsLog");
693     }
694     my $dbh = C4::Context->dbh;
695     my $query = 'DELETE FROM saved_sql WHERE id IN (' . join( ',', ('?') x @ids ) . ')';
696     my $sth = $dbh->prepare($query);
697     return $sth->execute(@ids);
698 }
699
700 sub get_saved_reports_base_query {
701     my $area_name_sql_snippet = get_area_name_sql_snippet;
702     return <<EOQ;
703 SELECT s.*, $area_name_sql_snippet, av_g.lib AS groupname, av_sg.lib AS subgroupname,
704 b.firstname AS borrowerfirstname, b.surname AS borrowersurname
705 FROM saved_sql s
706 LEFT JOIN saved_reports r ON r.report_id = s.id
707 LEFT OUTER JOIN authorised_values av_g ON (av_g.category = 'REPORT_GROUP' AND av_g.authorised_value = s.report_group)
708 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)
709 LEFT OUTER JOIN borrowers b USING (borrowernumber)
710 EOQ
711 }
712
713 sub get_saved_reports {
714 # $filter is either { date => $d, author => $a, keyword => $kw, }
715 # or $keyword. Optional.
716     my ($filter) = @_;
717     $filter = { keyword => $filter } if $filter && !ref( $filter );
718     my ($group, $subgroup) = @_;
719
720     my $dbh   = C4::Context->dbh();
721     my $query = get_saved_reports_base_query;
722     my (@cond,@args);
723     if ($filter) {
724         if (my $date = $filter->{date}) {
725             $date = eval { output_pref( { dt => dt_from_string( $date ), dateonly => 1, dateformat => 'iso' }); };
726             push @cond, "DATE(last_modified) = ? OR
727                          DATE(last_run) = ?";
728             push @args, $date, $date, $date;
729         }
730         if (my $author = $filter->{author}) {
731             $author = "%$author%";
732             push @cond, "surname LIKE ? OR
733                          firstname LIKE ?";
734             push @args, $author, $author;
735         }
736         if (my $keyword = $filter->{keyword}) {
737             push @cond, q|
738                        report LIKE ?
739                     OR report_name LIKE ?
740                     OR notes LIKE ?
741                     OR savedsql LIKE ?
742                     OR s.id = ?
743             |;
744             push @args, "%$keyword%", "%$keyword%", "%$keyword%", "%$keyword%", $keyword;
745         }
746         if ($filter->{group}) {
747             push @cond, "report_group = ?";
748             push @args, $filter->{group};
749         }
750         if ($filter->{subgroup}) {
751             push @cond, "report_subgroup = ?";
752             push @args, $filter->{subgroup};
753         }
754     }
755     $query .= " WHERE ".join( " AND ", map "($_)", @cond ) if @cond;
756     $query .= " GROUP BY s.id, s.borrowernumber, s.date_created, s.last_modified, s.savedsql, s.last_run, s.report_name, s.type, s.notes, s.cache_expiry, s.public, s.report_area, s.report_group, s.report_subgroup, s.mana_id, av_g.lib, av_sg.lib, b.firstname, b.surname";
757     $query .= " ORDER by date_created";
758
759     my $result = $dbh->selectall_arrayref($query, {Slice => {}}, @args);
760
761     return $result;
762 }
763
764 =head2 get_column_type($column)
765
766 This takes a column name of the format table.column and will return what type it is
767 (free text, set values, date)
768
769 =cut
770
771 sub get_column_type {
772         my ($tablecolumn) = @_;
773         my ($table,$column) = split(/\./,$tablecolumn);
774         my $dbh = C4::Context->dbh();
775         my $catalog;
776         my $schema;
777
778     # mysql doesn't support a column selection, set column to %
779         my $tempcolumn='%';
780         my $sth = $dbh->column_info( $catalog, $schema, $table, $tempcolumn ) || die $dbh->errstr;
781         while (my $info = $sth->fetchrow_hashref()){
782                 if ($info->{'COLUMN_NAME'} eq $column){
783                         #column we want
784                         if ($info->{'TYPE_NAME'} eq 'CHAR' || $info->{'TYPE_NAME'} eq 'VARCHAR'){
785                                 $info->{'TYPE_NAME'} = 'distinct';
786                         }
787                         return $info->{'TYPE_NAME'};            
788                 }
789         }
790 }
791
792 =head2 get_distinct_values($column)
793
794 Given a column name, return an arrary ref of hashrefs suitable for use as a tmpl_loop 
795 with the distinct values of the column
796
797 =cut
798
799 sub get_distinct_values {
800         my ($tablecolumn) = @_;
801         my ($table,$column) = split(/\./,$tablecolumn);
802         my $dbh = C4::Context->dbh();
803         my $query =
804           "SELECT distinct($column) as availablevalues FROM $table";
805         my $sth = $dbh->prepare($query);
806         $sth->execute();
807     return $sth->fetchall_arrayref({});
808 }       
809
810 sub save_dictionary {
811     my ( $name, $description, $sql, $area ) = @_;
812     my $dbh   = C4::Context->dbh();
813     my $query = "INSERT INTO reports_dictionary (name,description,saved_sql,report_area,date_created,date_modified)
814   VALUES (?,?,?,?,now(),now())";
815     my $sth = $dbh->prepare($query);
816     $sth->execute($name,$description,$sql,$area) || return 0;
817     return 1;
818 }
819
820 sub get_from_dictionary {
821     my ( $area, $id ) = @_;
822     my $dbh   = C4::Context->dbh();
823     my $area_name_sql_snippet = get_area_name_sql_snippet;
824     my $query = <<EOQ;
825 SELECT d.*, $area_name_sql_snippet
826 FROM reports_dictionary d
827 EOQ
828
829     if ($area) {
830         $query .= " WHERE report_area = ?";
831     } elsif ($id) {
832         $query .= " WHERE id = ?";
833     }
834     my $sth = $dbh->prepare($query);
835     if ($id) {
836         $sth->execute($id);
837     } elsif ($area) {
838         $sth->execute($area);
839     } else {
840         $sth->execute();
841     }
842     my @loop;
843     while ( my $data = $sth->fetchrow_hashref() ) {
844         push @loop, $data;
845     }
846     return ( \@loop );
847 }
848
849 sub delete_definition {
850         my ($id) = @_ or return;
851         my $dbh = C4::Context->dbh();
852         my $query = "DELETE FROM reports_dictionary WHERE id = ?";
853         my $sth = $dbh->prepare($query);
854         $sth->execute($id);
855 }
856
857 =head2 get_sql($report_id)
858
859 Given a report id, return the SQL statement for that report.
860 Otherwise, it just returns.
861
862 =cut
863
864 sub get_sql {
865         my ($id) = @_ or return;
866         my $dbh = C4::Context->dbh();
867         my $query = "SELECT * FROM saved_sql WHERE id = ?";
868         my $sth = $dbh->prepare($query);
869         $sth->execute($id);
870         my $data=$sth->fetchrow_hashref();
871         return $data->{'savedsql'};
872 }
873
874 sub get_results {
875     my ( $report_id ) = @_;
876     my $dbh = C4::Context->dbh;
877     return $dbh->selectall_arrayref(q|
878         SELECT id, report, date_run
879         FROM saved_reports
880         WHERE report_id = ?
881     |, { Slice => {} }, $report_id);
882 }
883
884 sub _get_column_defs {
885     my ($cgi) = @_;
886     my %columns;
887     my $columns_def_file = "columns.def";
888     my $htdocs = C4::Context->config('intrahtdocs');
889     my $section = 'intranet';
890
891     # We need the theme and the lang
892     # Since columns.def is not in the modules directory, we cannot sent it for the $tmpl var
893     my ($theme, $lang, $availablethemes) = C4::Templates::themelanguage($htdocs, 'about.tt', $section, $cgi);
894
895     my $full_path_to_columns_def_file="$htdocs/$theme/$lang/$columns_def_file";
896     open (my $fh, '<:encoding(utf-8)', $full_path_to_columns_def_file);
897     while ( my $input = <$fh> ){
898         chomp $input;
899         if ( $input =~ m|<field name="(.*)">(.*)</field>| ) {
900             my ( $field, $translation ) = ( $1, $2 );
901             $columns{$field} = $translation;
902         }
903     }
904     close $fh;
905     return \%columns;
906 }
907
908 =head2 GetReservedAuthorisedValues
909
910     my %reserved_authorised_values = GetReservedAuthorisedValues();
911
912 Returns a hash containig all reserved words
913
914 =cut
915
916 sub GetReservedAuthorisedValues {
917     my %reserved_authorised_values =
918             map { $_ => 1 } ( 'date',
919                               'branches',
920                               'itemtypes',
921                               'cn_source',
922                               'categorycode',
923                               'biblio_framework' );
924
925    return \%reserved_authorised_values;
926 }
927
928
929 =head2 IsAuthorisedValueValid
930
931     my $is_valid_ath_value = IsAuthorisedValueValid($authorised_value)
932
933 Returns 1 if $authorised_value is on the reserved authorised values list or
934 in the authorised value categories defined in
935
936 =cut
937
938 sub IsAuthorisedValueValid {
939
940     my $authorised_value = shift;
941     my $reserved_authorised_values = GetReservedAuthorisedValues();
942
943     if ( exists $reserved_authorised_values->{$authorised_value} ||
944          Koha::AuthorisedValues->search({ category => $authorised_value })->count ) {
945         return 1;
946     }
947
948     return 0;
949 }
950
951 =head2 GetParametersFromSQL
952
953     my @sql_parameters = GetParametersFromSQL($sql)
954
955 Returns an arrayref of hashes containing the keys name and authval
956
957 =cut
958
959 sub GetParametersFromSQL {
960
961     my $sql = shift ;
962     my @split = split(/<<|>>/,$sql);
963     my @sql_parameters = ();
964
965     for ( my $i = 0; $i < ($#split/2) ; $i++ ) {
966         my ($name,$authval) = split(/\|/,$split[$i*2+1]);
967         $authval =~ s/\:all$// if $authval;
968         push @sql_parameters, { 'name' => $name, 'authval' => $authval };
969     }
970
971     return \@sql_parameters;
972 }
973
974 =head2 ValidateSQLParameters
975
976     my @problematic_parameters = ValidateSQLParameters($sql)
977
978 Returns an arrayref of hashes containing the keys name and authval of
979 those SQL parameters that do not correspond to valid authorised names
980
981 =cut
982
983 sub ValidateSQLParameters {
984
985     my $sql = shift;
986     my @problematic_parameters = ();
987     my $sql_parameters = GetParametersFromSQL($sql);
988
989     foreach my $sql_parameter (@$sql_parameters) {
990         if ( defined $sql_parameter->{'authval'} ) {
991             push @problematic_parameters, $sql_parameter unless
992                 IsAuthorisedValueValid($sql_parameter->{'authval'});
993         }
994     }
995
996     return \@problematic_parameters;
997 }
998
999 =head2 EmailReport
1000
1001     my ( $emails, $arrayrefs ) = EmailReport($report_id, $letter_code, $module, $branch, $email)
1002
1003 Take a report and use it to process a Template Toolkit formatted notice
1004 Returns arrayrefs containing prepared letters and errors respectively
1005
1006 =cut
1007
1008 sub EmailReport {
1009
1010     my $params     = shift;
1011     my $report_id  = $params->{report_id};
1012     my $from       = $params->{from};
1013     my $email_col  = $params->{email} || 'email';
1014     my $module     = $params->{module};
1015     my $code       = $params->{code};
1016     my $branch     = $params->{branch} || "";
1017
1018     my @errors = ();
1019     my @emails = ();
1020
1021     return ( undef, [{ FATAL => "MISSING_PARAMS" }] ) unless ($report_id && $module && $code);
1022
1023     return ( undef, [{ FATAL => "NO_LETTER" }] ) unless
1024     my $letter = Koha::Notice::Templates->find({
1025         module     => $module,
1026         code       => $code,
1027         branchcode => $branch,
1028         message_transport_type => 'email',
1029     });
1030     $letter = $letter->unblessed;
1031
1032     my $report = Koha::Reports->find( $report_id );
1033     my $sql = $report->savedsql;
1034     return ( { FATAL => "NO_REPORT" } ) unless $sql;
1035
1036     my ( $sth, $errors ) = execute_query( $sql ); #don't pass offset or limit, hardcoded limit of 999,999 will be used
1037     return ( undef, [{ FATAL => "REPORT_FAIL" }] ) if $errors;
1038
1039     my $counter = 1;
1040     my $template = $letter->{content};
1041
1042     while ( my $row = $sth->fetchrow_hashref() ) {
1043         my $email;
1044         my $err_count = scalar @errors;
1045         push ( @errors, { NO_BOR_COL => $counter } ) unless defined $row->{borrowernumber};
1046         push ( @errors, { NO_EMAIL_COL => $counter } ) unless ( defined $row->{$email_col} );
1047         push ( @errors, { NO_FROM_COL => $counter } ) unless defined ( $from || $row->{from} );
1048         push ( @errors, { NO_BOR => $row->{borrowernumber} } ) unless Koha::Patrons->find({borrowernumber=>$row->{borrowernumber}});
1049
1050         my $from_address = $from || $row->{from};
1051         my $to_address = $row->{$email_col};
1052         push ( @errors, { NOT_PARSE => $counter } ) unless my $content = _process_row_TT( $row, $template );
1053         $counter++;
1054         next if scalar @errors > $err_count; #If any problems, try next
1055
1056         $letter->{content}       = $content;
1057         $email->{borrowernumber} = $row->{borrowernumber};
1058         $email->{letter}         = { %$letter };
1059         $email->{from_address}   = $from_address;
1060         $email->{to_address}     = $to_address;
1061
1062         push ( @emails, $email );
1063     }
1064
1065     return ( \@emails, \@errors );
1066
1067 }
1068
1069
1070
1071 =head2 ProcessRowTT
1072
1073    my $content = ProcessRowTT($row_hashref, $template);
1074
1075 Accepts a hashref containing values and processes them against Template Toolkit
1076 to produce content
1077
1078 =cut
1079
1080 sub _process_row_TT {
1081
1082     my ($row, $template) = @_;
1083
1084     return 0 unless ($row && $template);
1085     my $content;
1086     my $processor = Template->new();
1087     $processor->process( \$template, $row, \$content);
1088     return $content;
1089
1090 }
1091
1092 sub _get_display_value {
1093     my ( $original_value, $column ) = @_;
1094     if ( $column eq 'periodicity' ) {
1095         my $dbh = C4::Context->dbh();
1096         my $query = "SELECT description FROM subscription_frequencies WHERE id = ?";
1097         my $sth   = $dbh->prepare($query);
1098         $sth->execute($original_value);
1099         return $sth->fetchrow;
1100     }
1101     return $original_value;
1102 }
1103
1104
1105 =head3 convert_sql
1106
1107 my $updated_sql = C4::Reports::Guided::convert_sql( $sql );
1108
1109 Convert a sql query using biblioitems.marcxml to use the new
1110 biblio_metadata.metadata field instead
1111
1112 =cut
1113
1114 sub convert_sql {
1115     my ( $sql ) = @_;
1116     my $updated_sql = $sql;
1117     if ( $sql =~ m|biblioitems| and $sql =~ m|marcxml| ) {
1118         $updated_sql =~ s|biblioitems|biblio_metadata|g;
1119         $updated_sql =~ s|marcxml|metadata|g;
1120     }
1121     return $updated_sql;
1122 }
1123
1124 1;
1125 __END__
1126
1127 =head1 AUTHOR
1128
1129 Chris Cormack <crc@liblime.com>
1130
1131 =cut