Bug 16829: make logaction and GetLogs aware of the interface column
[koha.git] / C4 / Log.pm
1 package C4::Log;
2
3 #package to deal with Logging Actions in DB
4
5
6 # Copyright 2000-2002 Katipo Communications
7 # Copyright 2011 MJ Ray and software.coop
8 #
9 # This file is part of Koha.
10 #
11 # Koha is free software; you can redistribute it and/or modify it
12 # under the terms of the GNU General Public License as published by
13 # the Free Software Foundation; either version 3 of the License, or
14 # (at your option) any later version.
15 #
16 # Koha is distributed in the hope that it will be useful, but
17 # WITHOUT ANY WARRANTY; without even the implied warranty of
18 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 # GNU General Public License for more details.
20 #
21 # You should have received a copy of the GNU General Public License
22 # along with Koha; if not, see <http://www.gnu.org/licenses>.
23
24 use strict;
25 use warnings;
26
27 use JSON qw( to_json );
28
29 use C4::Context;
30 use Koha::DateUtils;
31 use Koha::Logger;
32
33 use vars qw(@ISA @EXPORT);
34
35 BEGIN {
36         require Exporter;
37         @ISA = qw(Exporter);
38         @EXPORT = qw(&logaction &cronlogaction &GetLogStatus &displaylog &GetLogs);
39 }
40
41 =head1 NAME
42
43 C4::Log - Koha Log Facility functions
44
45 =head1 SYNOPSIS
46
47   use C4::Log;
48
49 =head1 DESCRIPTION
50
51 The functions in this module perform various functions in order to log all the operations done on the Database, including deleting and undeleting books, adding/editing members, etc.
52
53 =head1 FUNCTIONS
54
55 =over 2
56
57 =item logaction
58
59   &logaction($modulename, $actionname, $objectnumber, $infos);
60
61 Adds a record into action_logs table to report the different changes upon the database.
62 Each log entry includes the number of the user currently logged in.  For batch
63 jobs, which operate without authenticating a user and setting up a session, the user
64 number is set to 0, which is the same as the superlibrarian's number.
65
66 =cut
67
68 #'
69 sub logaction {
70     my ($modulename, $actionname, $objectnumber, $infos, $interface)=@_;
71
72     # Get ID of logged in user.  if called from a batch job,
73     # no user session exists and C4::Context->userenv() returns
74     # the scalar '0'.
75     my $userenv = C4::Context->userenv();
76     my $usernumber = (ref($userenv) eq 'HASH') ? $userenv->{'number'} : 0;
77     $usernumber ||= 0;
78     $interface //= C4::Context->interface;
79
80     my $dbh = C4::Context->dbh;
81     my $sth=$dbh->prepare("Insert into action_logs (timestamp,user,module,action,object,info,interface) values (now(),?,?,?,?,?,?)");
82     $sth->execute($usernumber,$modulename,$actionname,$objectnumber,$infos,$interface);
83     $sth->finish;
84
85     my $logger = Koha::Logger->get(
86         {
87             interface => 'intranet',
88             category  => "ActionLogs.$modulename.$actionname"
89         }
90     );
91     $logger->debug(
92         sub {
93             "ACTION LOG: " . to_json(
94                 {
95                     user   => $usernumber,
96                     module => $modulename,
97                     action => $actionname,
98                     object => $objectnumber,
99                     info   => $infos
100                 }
101             );
102         }
103     );
104 }
105
106 =item cronlogaction
107
108   &cronlogaction($infos);
109
110 Convenience routine to add a record into action_logs table from a cron job.
111 Logs the path and name of the calling script plus the information privided by param $infos.
112
113 =cut
114
115 #'
116 sub cronlogaction {
117     my ($infos)=@_;
118     my $loginfo = (caller(0))[1];
119     $loginfo .= ' ' . $infos if $infos;
120     logaction( 'CRONJOBS', 'Run', undef, $loginfo ) if C4::Context->preference('CronjobLog');
121 }
122
123
124 =item GetLogStatus
125
126   $status = GetLogStatus;
127
128 C<$status> is a hasref like this example:
129     $hash = {
130         BorrowersLog   => 1,
131         CataloguingLog => 0,
132         IssueLog       => 0,
133         ...
134     }
135
136 =cut
137
138 #'
139 sub GetLogStatus {
140     my %hash;
141     $hash{BorrowersLog}    = C4::Context->preference("BorrowersLog");
142     $hash{CataloguingLog}  = C4::Context->preference("CataloguingLog");
143     $hash{IssueLog}        = C4::Context->preference("IssueLog");
144     $hash{ReturnLog}       = C4::Context->preference("ReturnLog");
145     $hash{SubscriptionLog} = C4::Context->preference("SubscriptionLog");
146     $hash{LetterLog}       = C4::Context->preference("LetterLog");
147     $hash{FinesLog}        = C4::Context->preference("FinesLog");
148     return \%hash;
149 }
150
151 =item displaylog
152
153   &displaylog($modulename, @filters);
154   $modulename is the name of the module on which the user wants to display logs
155   @filters is an optional table of hash containing :
156       - name : the name of the variable to filter
157     - value : the value of the filter.... May be with * joker
158
159 returns a table of hash containing who did what on which object at what time
160
161 =cut
162
163 #'
164 sub displaylog {
165   my ($modulename, @filters) = @_;
166     my $dbh = C4::Context->dbh;
167     my $strsth=qq|
168                 SELECT action_logs.timestamp, action_logs.action, action_logs.info,
169                                 borrowers.cardnumber, borrowers.surname, borrowers.firstname, borrowers.userid,
170                         biblio.biblionumber, biblio.title, biblio.author
171         FROM action_logs
172                 LEFT JOIN borrowers ON borrowers.borrowernumber=action_logs.user
173         LEFT JOIN  biblio   ON action_logs.object=biblio.biblionumber
174         WHERE action_logs.module = 'cataloguing'
175         |;
176         my %filtermap = ();
177     if ($modulename eq "catalogue" or $modulename eq "acqui") {
178                 %filtermap = (
179                           user => 'borrowers.surname',
180                          title => 'biblio.title',
181                         author => 'biblio.author',
182                 );
183     } elsif ($modulename eq "members") {
184         $strsth=qq|
185                 SELECT action_logs.timestamp, action_logs.action, action_logs.info,
186                         borrowers.cardnumber, borrowers.surname, borrowers.firstname, borrowers.userid,
187                         bor2.cardnumber, bor2.surname, bor2.firstname, bor2.userid
188         FROM action_logs
189                 LEFT JOIN borrowers ON borrowers.borrowernumber=action_logs.user
190                 LEFT JOIN borrowers as bor2 ON action_logs.object=bor2.borrowernumber
191         WHERE action_logs.module = 'members'
192                 |;
193                 %filtermap = (
194                        user => 'borrowers.surname',
195                     surname => 'bor2.surname',
196                   firstname => 'bor2.firstname',
197                  cardnumber => 'bor2.cardnumber',
198                 );
199     } else {
200                 return 0;
201         }
202
203     if (@filters) {
204                 foreach my $filter (@filters) {
205                         my $tempname = $filter->{name}         or next;
206                         (grep {/^$tempname$/} keys %filtermap) or next;
207                         $filter->{value} =~ s/\*/%/g;
208                         $strsth .= " AND " . $filtermap{$tempname} . " LIKE " . $filter->{value};
209                 }
210         }
211     my $sth=$dbh->prepare($strsth);
212     $sth->execute;
213     my @results;
214     my $count;
215     my $hilighted=1;
216     while (my $data = $sth->fetchrow_hashref){
217         $data->{hilighted} = ($hilighted>0);
218         $data->{info} =~ s/\n/<br\/>/g;
219         $data->{day} = output_pref({ str => $data->{timestamp} });
220         push @results, $data;
221         $count++;
222         $hilighted = -$hilighted;
223     }
224     return ($count, \@results);
225 }
226
227 =item GetLogs
228
229 $logs = GetLogs($datefrom,$dateto,$user,\@modules,$action,$object,$info);
230
231 Return:
232 C<$logs> is a ref to a hash which containts all columns from action_logs
233
234 =cut
235
236 sub GetLogs {
237     my $datefrom = shift;
238     my $dateto   = shift;
239     my $user     = shift;
240     my $modules  = shift;
241     my $action   = shift;
242     my $object   = shift;
243     my $info     = shift;
244     my $interfaces = shift;
245
246     my $iso_datefrom = $datefrom ? output_pref({ dt => dt_from_string( $datefrom ), dateformat => 'iso', dateonly => 1 }) : undef;
247     my $iso_dateto = $dateto ? output_pref({ dt => dt_from_string( $dateto ), dateformat => 'iso', dateonly => 1 }) : undef;
248
249     $user ||= q{};
250
251     my $dbh   = C4::Context->dbh;
252     my $query = "
253         SELECT *
254         FROM   action_logs
255         WHERE 1
256     ";
257
258     my @parameters;
259     $query .=
260       " AND DATE_FORMAT(timestamp, '%Y-%m-%d') >= \"" . $iso_datefrom . "\" "
261       if $iso_datefrom;    #fix me - mysql specific
262     $query .=
263       " AND DATE_FORMAT(timestamp, '%Y-%m-%d') <= \"" . $iso_dateto . "\" "
264       if $iso_dateto;
265     if ( $user ne q{} ) {
266         $query .= " AND user = ? ";
267         push( @parameters, $user );
268     }
269     if ( $modules && scalar(@$modules) ) {
270         $query .=
271           " AND module IN (" . join( ",", map { "?" } @$modules ) . ") ";
272         push( @parameters, @$modules );
273     }
274     if ( $action && scalar(@$action) ) {
275         $query .= " AND action IN (" . join( ",", map { "?" } @$action ) . ") ";
276         push( @parameters, @$action );
277     }
278     if ($object) {
279         $query .= " AND object = ? ";
280         push( @parameters, $object );
281     }
282     if ($info) {
283         $query .= " AND info LIKE ? ";
284         push( @parameters, "%" . $info . "%" );
285     }
286     if ( $interfaces && scalar(@$interfaces) ) {
287         $query .=
288           " AND interface IN (" . join( ",", map { "?" } @$interfaces ) . ") ";
289         push( @parameters, @$interfaces );
290     }
291
292     my $sth = $dbh->prepare($query);
293     $sth->execute(@parameters);
294
295     my @logs;
296     while ( my $row = $sth->fetchrow_hashref ) {
297         push @logs, $row;
298     }
299     return \@logs;
300 }
301
302 1;
303 __END__
304
305 =back
306
307 =head1 AUTHOR
308
309 Koha Development Team <http://koha-community.org/>
310
311 =cut