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