Bug 30110: Fix concatenation during assignements
[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 execute_query
468
469   ($sth, $error) = execute_query($sql, $offset, $limit[, \@sql_params])
470
471
472 This function returns a DBI statement handler from which the caller can
473 fetch the results of the SQL passed via C<$sql>.
474
475 If passed any query other than a SELECT, or if there is a DB error,
476 C<$errors> is returned, and is a hashref containing the error after this
477 manner:
478
479 C<$error->{'sqlerr'}> contains the offending SQL keyword.
480 C<$error->{'queryerr'}> contains the native db engine error returned
481 for the query.
482
483 C<$offset>, and C<$limit> are required parameters.
484
485 C<\@sql_params> is an optional list of parameter values to paste in.
486 The caller is responsible for making sure that C<$sql> has placeholders
487 and that the number placeholders matches the number of parameters.
488
489 =cut
490
491 # returns $sql, $offset, $limit
492 # $sql returned will be transformed to:
493 #  ~ remove any LIMIT clause
494 #  ~ repace SELECT clause w/ SELECT count(*)
495
496 sub select_2_select_count {
497     # Modify the query passed in to create a count query... (I think this covers all cases -crn)
498     my ($sql) = strip_limit(shift) or return;
499     $sql =~ s/\bSELECT\W+(?:\w+\W+){1,}?FROM\b|\bSELECT\W\*\WFROM\b/SELECT count(*) FROM /ig;
500     return $sql;
501 }
502
503 # This removes the LIMIT from the query so that a custom one can be specified.
504 # Usage:
505 #   ($new_sql, $offset, $limit) = strip_limit($sql);
506 #
507 # Where:
508 #   $sql is the query to modify
509 #   $new_sql is the resulting query
510 #   $offset is the offset value, if the LIMIT was the two-argument form,
511 #       0 if it wasn't otherwise given.
512 #   $limit is the limit value
513 #
514 # Notes:
515 #   * This makes an effort to not break subqueries that have their own
516 #     LIMIT specified. It does that by only removing a LIMIT if it comes after
517 #     a WHERE clause (which isn't perfect, but at least should make more cases
518 #     work - subqueries with a limit in the WHERE will still break.)
519 #   * If your query doesn't have a WHERE clause then all LIMITs will be
520 #     removed. This may break some subqueries, but is hopefully rare enough
521 #     to not be a big issue.
522 sub strip_limit {
523     my ($sql) = @_;
524
525     return unless $sql;
526     return ($sql, 0, undef) unless $sql =~ /\bLIMIT\b/i;
527
528     # Two options: if there's no WHERE clause in the SQL, we simply capture
529     # any LIMIT that's there. If there is a WHERE, we make sure that we only
530     # capture a LIMIT after the last one. This prevents stomping on subqueries.
531     if ($sql !~ /\bWHERE\b/i) {
532         (my $res = $sql) =~ s/\bLIMIT\b\s*(\d+)(\s*\,\s*(\d+))?\s*/ /ig;
533         return ($res, (defined $2 ? $1 : 0), (defined $3 ? $3 : $1));
534     } else {
535         my $res = $sql;
536         $res =~ m/.*\bWHERE\b/gsi;
537         $res =~ s/\G(.*)\bLIMIT\b\s*(\d+)(\s*\,\s*(\d+))?\s*/$1 /is;
538         return ($res, (defined $3 ? $2 : 0), (defined $4 ? $4 : $2));
539     }
540 }
541
542 sub execute_query {
543
544     my ( $sql, $offset, $limit, $sql_params, $report_id ) = @_;
545
546     $sql_params = [] unless defined $sql_params;
547
548     # check parameters
549     unless ($sql) {
550         carp "execute_query() called without SQL argument";
551         return;
552     }
553     $offset = 0    unless $offset;
554     $limit  = 999999 unless $limit;
555
556     Koha::Logger->get->debug("Report - execute_query($sql, $offset, $limit)");
557
558     my ( $is_sql_valid, $errors ) = Koha::Report->new({ savedsql => $sql })->is_sql_valid;
559     return (undef, @{$errors}[0]) unless $is_sql_valid;
560
561     foreach my $sql_param ( @$sql_params ){
562         if ( $sql_param =~ m/\n/ ){
563             my @list = split /\n/, $sql_param;
564             my @quoted_list;
565             foreach my $item ( @list ){
566                 $item =~ s/\r//;
567               push @quoted_list, C4::Context->dbh->quote($item);
568             }
569             $sql_param = "(".join(",",@quoted_list).")";
570         }
571     }
572
573     my ($useroffset, $userlimit);
574
575     # Grab offset/limit from user supplied LIMIT and drop the LIMIT so we can control pagination
576     ($sql, $useroffset, $userlimit) = strip_limit($sql);
577
578     Koha::Logger->get->debug(
579         sprintf "User has supplied (OFFSET,) LIMIT = %s, %s",
580         $useroffset, ( defined($userlimit) ? $userlimit : 'UNDEF' ) );
581
582     $offset += $useroffset;
583     if (defined($userlimit)) {
584         if ($offset + $limit > $userlimit ) {
585             $limit = $userlimit - $offset;
586         } elsif ( ! $offset && $limit < $userlimit ) {
587             $limit = $userlimit;
588         }
589     }
590     $sql .= " LIMIT ?, ?";
591
592     my $dbh = C4::Context->dbh;
593
594     $dbh->do( 'UPDATE saved_sql SET last_run = NOW() WHERE id = ?', undef, $report_id ) if $report_id;
595
596     my $sth = $dbh->prepare($sql);
597     eval {
598         $sth->execute(@$sql_params, $offset, $limit);
599     };
600     warn $@ if $@;
601
602     return ( $sth, { queryerr => $sth->errstr } ) if ($sth->err);
603     return ( $sth );
604 }
605
606 =head2 save_report($sql,$name,$type,$notes)
607
608 Given some sql and a name this will saved it so that it can reused
609 Returns id of the newly created report
610
611 =cut
612
613 sub save_report {
614     my ($fields) = @_;
615     my $borrowernumber = $fields->{borrowernumber};
616     my $sql = $fields->{sql};
617     my $name = $fields->{name};
618     my $type = $fields->{type};
619     my $notes = $fields->{notes};
620     my $area = $fields->{area};
621     my $group = $fields->{group};
622     my $subgroup = $fields->{subgroup};
623     my $cache_expiry = $fields->{cache_expiry};
624     my $public = $fields->{public};
625
626     $sql =~ s/(\s*\;\s*)$//;    # removes trailing whitespace and /;/
627     my $now = dt_from_string;
628     my $report = Koha::Report->new(
629         {
630             borrowernumber  => $borrowernumber,
631             date_created    => $now, # Must be moved to Koha::Report->store
632             last_modified   => $now, # Must be moved to Koha::Report->store
633             savedsql        => $sql,
634             report_name     => $name,
635             report_area     => $area,
636             report_group    => $group,
637             report_subgroup => $subgroup,
638             type            => $type,
639             notes           => $notes,
640             cache_expiry    => $cache_expiry,
641             public          => $public,
642         }
643     )->store;
644
645     return $report->id;
646 }
647
648 sub update_sql {
649     my $id         = shift || croak "No Id given";
650     my $fields     = shift;
651     my $sql = $fields->{sql};
652     my $name = $fields->{name};
653     my $notes = $fields->{notes};
654     my $group = $fields->{group};
655     my $subgroup = $fields->{subgroup};
656     my $cache_expiry = $fields->{cache_expiry};
657     my $public = $fields->{public};
658
659     $sql =~ s/(\s*\;\s*)$//;    # removes trailing whitespace and /;/
660     my $report = Koha::Reports->find($id);
661     $report->last_modified(dt_from_string);
662     $report->savedsql($sql);
663     $report->report_name($name);
664     $report->notes($notes);
665     $report->report_group($group);
666     $report->report_subgroup($subgroup);
667     $report->cache_expiry($cache_expiry) if defined $cache_expiry;
668     $report->public($public);
669     $report->store();
670     if( $cache_expiry >= 2592000 ){
671       die "Please specify a cache expiry less than 30 days\n"; # That's a bit harsh
672     }
673
674     return $report;
675 }
676
677 sub store_results {
678     my ( $id, $json ) = @_;
679     my $dbh = C4::Context->dbh();
680     $dbh->do(q|
681         INSERT INTO saved_reports ( report_id, report, date_run ) VALUES ( ?, ?, NOW() );
682     |, undef, $id, $json );
683 }
684
685 sub format_results {
686     my ( $id ) = @_;
687     my $dbh = C4::Context->dbh();
688     my ( $report_name, $notes, $json, $date_run ) = $dbh->selectrow_array(q|
689        SELECT ss.report_name, ss.notes, sr.report, sr.date_run
690        FROM saved_sql ss
691        LEFT JOIN saved_reports sr ON sr.report_id = ss.id
692        WHERE sr.id = ?
693     |, undef, $id);
694     return {
695         report_name => $report_name,
696         notes => $notes,
697         results => from_json( $json ),
698         date_run => $date_run,
699     };
700 }
701
702 sub delete_report {
703     my (@ids) = @_;
704     return unless @ids;
705     foreach my $id (@ids) {
706         my $data = Koha::Reports->find($id);
707         logaction( "REPORTS", "DELETE", $id, $data->report_name." | ".$data->savedsql ) if C4::Context->preference("ReportsLog");
708     }
709     my $dbh = C4::Context->dbh;
710     my $query = 'DELETE FROM saved_sql WHERE id IN (' . join( ',', ('?') x @ids ) . ')';
711     my $sth = $dbh->prepare($query);
712     return $sth->execute(@ids);
713 }
714
715 sub get_saved_reports_base_query {
716     my $area_name_sql_snippet = get_area_name_sql_snippet;
717     return <<EOQ;
718 SELECT s.*, $area_name_sql_snippet, av_g.lib AS groupname, av_sg.lib AS subgroupname,
719 b.firstname AS borrowerfirstname, b.surname AS borrowersurname
720 FROM saved_sql s
721 LEFT JOIN saved_reports r ON r.report_id = s.id
722 LEFT OUTER JOIN authorised_values av_g ON (av_g.category = 'REPORT_GROUP' AND av_g.authorised_value = s.report_group)
723 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)
724 LEFT OUTER JOIN borrowers b USING (borrowernumber)
725 EOQ
726 }
727
728 sub get_saved_reports {
729 # $filter is either { date => $d, author => $a, keyword => $kw, }
730 # or $keyword. Optional.
731     my ($filter) = @_;
732     $filter = { keyword => $filter } if $filter && !ref( $filter );
733     my ($group, $subgroup) = @_;
734
735     my $dbh   = C4::Context->dbh();
736     my $query = get_saved_reports_base_query;
737     my (@cond,@args);
738     if ($filter) {
739         if (my $date = $filter->{date}) {
740             $date = eval { output_pref( { dt => dt_from_string( $date ), dateonly => 1, dateformat => 'iso' }); };
741             push @cond, "DATE(last_modified) = ? OR
742                          DATE(last_run) = ?";
743             push @args, $date, $date;
744         }
745         if (my $author = $filter->{author}) {
746             $author = "%$author%";
747             push @cond, "surname LIKE ? OR
748                          firstname LIKE ?";
749             push @args, $author, $author;
750         }
751         if (my $keyword = $filter->{keyword}) {
752             push @cond, q|
753                        report LIKE ?
754                     OR report_name LIKE ?
755                     OR notes LIKE ?
756                     OR savedsql LIKE ?
757                     OR s.id = ?
758             |;
759             push @args, "%$keyword%", "%$keyword%", "%$keyword%", "%$keyword%", $keyword;
760         }
761         if ($filter->{group}) {
762             push @cond, "report_group = ?";
763             push @args, $filter->{group};
764         }
765         if ($filter->{subgroup}) {
766             push @cond, "report_subgroup = ?";
767             push @args, $filter->{subgroup};
768         }
769     }
770     $query .= " WHERE ".join( " AND ", map "($_)", @cond ) if @cond;
771     $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";
772     $query .= " ORDER by date_created";
773
774     my $result = $dbh->selectall_arrayref($query, {Slice => {}}, @args);
775
776     return $result;
777 }
778
779 =head2 get_column_type($column)
780
781 This takes a column name of the format table.column and will return what type it is
782 (free text, set values, date)
783
784 =cut
785
786 sub get_column_type {
787         my ($tablecolumn) = @_;
788         my ($table,$column) = split(/\./,$tablecolumn);
789         my $dbh = C4::Context->dbh();
790         my $catalog;
791         my $schema;
792
793     # mysql doesn't support a column selection, set column to %
794         my $tempcolumn='%';
795         my $sth = $dbh->column_info( $catalog, $schema, $table, $tempcolumn ) || die $dbh->errstr;
796         while (my $info = $sth->fetchrow_hashref()){
797                 if ($info->{'COLUMN_NAME'} eq $column){
798                         #column we want
799                         if ($info->{'TYPE_NAME'} eq 'CHAR' || $info->{'TYPE_NAME'} eq 'VARCHAR'){
800                                 $info->{'TYPE_NAME'} = 'distinct';
801                         }
802                         return $info->{'TYPE_NAME'};            
803                 }
804         }
805 }
806
807 =head2 get_distinct_values($column)
808
809 Given a column name, return an arrary ref of hashrefs suitable for use as a tmpl_loop 
810 with the distinct values of the column
811
812 =cut
813
814 sub get_distinct_values {
815         my ($tablecolumn) = @_;
816         my ($table,$column) = split(/\./,$tablecolumn);
817         my $dbh = C4::Context->dbh();
818         my $query =
819           "SELECT distinct($column) as availablevalues FROM $table";
820         my $sth = $dbh->prepare($query);
821         $sth->execute();
822     return $sth->fetchall_arrayref({});
823 }       
824
825 sub save_dictionary {
826     my ( $name, $description, $sql, $area ) = @_;
827     my $dbh   = C4::Context->dbh();
828     my $query = "INSERT INTO reports_dictionary (name,description,saved_sql,report_area,date_created,date_modified)
829   VALUES (?,?,?,?,now(),now())";
830     my $sth = $dbh->prepare($query);
831     $sth->execute($name,$description,$sql,$area) || return 0;
832     return 1;
833 }
834
835 sub get_from_dictionary {
836     my ( $area, $id ) = @_;
837     my $dbh   = C4::Context->dbh();
838     my $area_name_sql_snippet = get_area_name_sql_snippet;
839     my $query = <<EOQ;
840 SELECT d.*, $area_name_sql_snippet
841 FROM reports_dictionary d
842 EOQ
843
844     if ($area) {
845         $query .= " WHERE report_area = ?";
846     } elsif ($id) {
847         $query .= " WHERE id = ?";
848     }
849     my $sth = $dbh->prepare($query);
850     if ($id) {
851         $sth->execute($id);
852     } elsif ($area) {
853         $sth->execute($area);
854     } else {
855         $sth->execute();
856     }
857     my @loop;
858     while ( my $data = $sth->fetchrow_hashref() ) {
859         push @loop, $data;
860     }
861     return ( \@loop );
862 }
863
864 sub delete_definition {
865         my ($id) = @_ or return;
866         my $dbh = C4::Context->dbh();
867         my $query = "DELETE FROM reports_dictionary WHERE id = ?";
868         my $sth = $dbh->prepare($query);
869         $sth->execute($id);
870 }
871
872 =head2 get_sql($report_id)
873
874 Given a report id, return the SQL statement for that report.
875 Otherwise, it just returns.
876
877 =cut
878
879 sub get_sql {
880         my ($id) = @_ or return;
881         my $dbh = C4::Context->dbh();
882         my $query = "SELECT * FROM saved_sql WHERE id = ?";
883         my $sth = $dbh->prepare($query);
884         $sth->execute($id);
885         my $data=$sth->fetchrow_hashref();
886         return $data->{'savedsql'};
887 }
888
889 sub get_results {
890     my ( $report_id ) = @_;
891     my $dbh = C4::Context->dbh;
892     return $dbh->selectall_arrayref(q|
893         SELECT id, report, date_run
894         FROM saved_reports
895         WHERE report_id = ?
896     |, { Slice => {} }, $report_id);
897 }
898
899 sub _get_column_defs {
900     my ($cgi) = @_;
901     my %columns;
902     my $columns_def_file = "columns.def";
903     my $htdocs = C4::Context->config('intrahtdocs');
904     my $section = 'intranet';
905
906     # We need the theme and the lang
907     # Since columns.def is not in the modules directory, we cannot sent it for the $tmpl var
908     my ($theme, $lang, $availablethemes) = C4::Templates::themelanguage($htdocs, 'about.tt', $section, $cgi);
909
910     my $full_path_to_columns_def_file="$htdocs/$theme/$lang/$columns_def_file";
911     open (my $fh, '<:encoding(utf-8)', $full_path_to_columns_def_file);
912     while ( my $input = <$fh> ){
913         chomp $input;
914         if ( $input =~ m|<field name="(.*)">(.*)</field>| ) {
915             my ( $field, $translation ) = ( $1, $2 );
916             $columns{$field} = $translation;
917         }
918     }
919     close $fh;
920     return \%columns;
921 }
922
923 =head2 GetReservedAuthorisedValues
924
925     my %reserved_authorised_values = GetReservedAuthorisedValues();
926
927 Returns a hash containig all reserved words
928
929 =cut
930
931 sub GetReservedAuthorisedValues {
932     my %reserved_authorised_values =
933             map { $_ => 1 } ( 'date',
934                               'list',
935                               'branches',
936                               'itemtypes',
937                               'cn_source',
938                               'categorycode',
939                               'biblio_framework',
940                               'cash_registers',
941                               'debit_types',
942                               'credit_types' );
943
944    return \%reserved_authorised_values;
945 }
946
947
948 =head2 IsAuthorisedValueValid
949
950     my $is_valid_ath_value = IsAuthorisedValueValid($authorised_value)
951
952 Returns 1 if $authorised_value is on the reserved authorised values list or
953 in the authorised value categories defined in
954
955 =cut
956
957 sub IsAuthorisedValueValid {
958
959     my $authorised_value = shift;
960     my $reserved_authorised_values = GetReservedAuthorisedValues();
961
962     if ( exists $reserved_authorised_values->{$authorised_value} ||
963          Koha::AuthorisedValues->search({ category => $authorised_value })->count ) {
964         return 1;
965     }
966
967     return 0;
968 }
969
970 =head2 GetParametersFromSQL
971
972     my @sql_parameters = GetParametersFromSQL($sql)
973
974 Returns an arrayref of hashes containing the keys name and authval
975
976 =cut
977
978 sub GetParametersFromSQL {
979
980     my $sql = shift ;
981     my @split = split(/<<|>>/,$sql);
982     my @sql_parameters = ();
983
984     for ( my $i = 0; $i < ($#split/2) ; $i++ ) {
985         my ($name,$authval) = split(/\|/,$split[$i*2+1]);
986         $authval =~ s/\:all$// if $authval;
987         push @sql_parameters, { 'name' => $name, 'authval' => $authval };
988     }
989
990     return \@sql_parameters;
991 }
992
993 =head2 ValidateSQLParameters
994
995     my @problematic_parameters = ValidateSQLParameters($sql)
996
997 Returns an arrayref of hashes containing the keys name and authval of
998 those SQL parameters that do not correspond to valid authorised names
999
1000 =cut
1001
1002 sub ValidateSQLParameters {
1003
1004     my $sql = shift;
1005     my @problematic_parameters = ();
1006     my $sql_parameters = GetParametersFromSQL($sql);
1007
1008     foreach my $sql_parameter (@$sql_parameters) {
1009         if ( defined $sql_parameter->{'authval'} ) {
1010             push @problematic_parameters, $sql_parameter unless
1011                 IsAuthorisedValueValid($sql_parameter->{'authval'});
1012         }
1013     }
1014
1015     return \@problematic_parameters;
1016 }
1017
1018 =head2 EmailReport
1019
1020     my ( $emails, $arrayrefs ) = EmailReport($report_id, $letter_code, $module, $branch, $email)
1021
1022 Take a report and use it to process a Template Toolkit formatted notice
1023 Returns arrayrefs containing prepared letters and errors respectively
1024
1025 =cut
1026
1027 sub EmailReport {
1028
1029     my $params     = shift;
1030     my $report_id  = $params->{report_id};
1031     my $from       = $params->{from};
1032     my $email_col  = $params->{email} || 'email';
1033     my $module     = $params->{module};
1034     my $code       = $params->{code};
1035     my $branch     = $params->{branch} || "";
1036
1037     my @errors = ();
1038     my @emails = ();
1039
1040     return ( undef, [{ FATAL => "MISSING_PARAMS" }] ) unless ($report_id && $module && $code);
1041
1042     return ( undef, [{ FATAL => "NO_LETTER" }] ) unless
1043     my $letter = Koha::Notice::Templates->find({
1044         module     => $module,
1045         code       => $code,
1046         branchcode => $branch,
1047         message_transport_type => 'email',
1048     });
1049     $letter = $letter->unblessed;
1050     $letter->{'content-type'} = 'text/html; charset="UTF-8"' if $letter->{'is_html'};
1051
1052     my $report = Koha::Reports->find( $report_id );
1053     my $sql = $report->savedsql;
1054     return ( { FATAL => "NO_REPORT" } ) unless $sql;
1055
1056     my ( $sth, $errors ) = execute_query( $sql ); #don't pass offset or limit, hardcoded limit of 999,999 will be used
1057     return ( undef, [{ FATAL => "REPORT_FAIL" }] ) if $errors;
1058
1059     my $counter = 1;
1060     my $template = $letter->{content};
1061
1062     while ( my $row = $sth->fetchrow_hashref() ) {
1063         my $email;
1064         my $err_count = scalar @errors;
1065         push ( @errors, { NO_BOR_COL => $counter } ) unless defined $row->{borrowernumber};
1066         push ( @errors, { NO_EMAIL_COL => $counter } ) unless ( defined $row->{$email_col} );
1067         push ( @errors, { NO_FROM_COL => $counter } ) unless defined ( $from || $row->{from} );
1068         push ( @errors, { NO_BOR => $row->{borrowernumber} } ) unless Koha::Patrons->find({borrowernumber=>$row->{borrowernumber}});
1069
1070         my $from_address = $from || $row->{from};
1071         my $to_address = $row->{$email_col};
1072         push ( @errors, { NOT_PARSE => $counter } ) unless my $content = _process_row_TT( $row, $template );
1073         $counter++;
1074         next if scalar @errors > $err_count; #If any problems, try next
1075
1076         $letter->{content}       = $content;
1077         $email->{borrowernumber} = $row->{borrowernumber};
1078         $email->{letter}         = { %$letter };
1079         $email->{from_address}   = $from_address;
1080         $email->{to_address}     = $to_address;
1081
1082         push ( @emails, $email );
1083     }
1084
1085     return ( \@emails, \@errors );
1086
1087 }
1088
1089
1090
1091 =head2 ProcessRowTT
1092
1093    my $content = ProcessRowTT($row_hashref, $template);
1094
1095 Accepts a hashref containing values and processes them against Template Toolkit
1096 to produce content
1097
1098 =cut
1099
1100 sub _process_row_TT {
1101
1102     my ($row, $template) = @_;
1103
1104     return 0 unless ($row && $template);
1105     my $content;
1106     my $processor = Template->new();
1107     $processor->process( \$template, $row, \$content);
1108     return $content;
1109
1110 }
1111
1112 sub _get_display_value {
1113     my ( $original_value, $column ) = @_;
1114     if ( $column eq 'periodicity' ) {
1115         my $dbh = C4::Context->dbh();
1116         my $query = "SELECT description FROM subscription_frequencies WHERE id = ?";
1117         my $sth   = $dbh->prepare($query);
1118         $sth->execute($original_value);
1119         return $sth->fetchrow;
1120     }
1121     return $original_value;
1122 }
1123
1124
1125 =head3 convert_sql
1126
1127 my $updated_sql = C4::Reports::Guided::convert_sql( $sql );
1128
1129 Convert a sql query using biblioitems.marcxml to use the new
1130 biblio_metadata.metadata field instead
1131
1132 =cut
1133
1134 sub convert_sql {
1135     my ( $sql ) = @_;
1136     my $updated_sql = $sql;
1137     if ( $sql =~ m|biblioitems| and $sql =~ m|marcxml| ) {
1138         $updated_sql =~ s|biblioitems|biblio_metadata|g;
1139         $updated_sql =~ s|marcxml|metadata|g;
1140     }
1141     return $updated_sql;
1142 }
1143
1144 1;
1145 __END__
1146
1147 =head1 AUTHOR
1148
1149 Chris Cormack <crc@liblime.com>
1150
1151 =cut