Bug 8917 : Script to log link clicks
[koha.git] / opac / tracklinks.pl
1 #!/usr/bin/perl
2
3 # script to log clicks on links to external urls
4
5 # Copyright 2012 Catalyst IT
6 # This file is part of Koha.
7 #
8 # Koha is free software; you can redistribute it and/or modify it under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 2 of the License, or (at your option) any later
11 # version.
12 #
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License along
18 # with Koha; if not, write to the Free Software Foundation, Inc.,
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20
21 use Modern::Perl;
22 use C4::Context;
23 use C4::Auth qw(checkauth);
24 use CGI;
25
26 my $trackinglinks = C4::Context->preference('TrackClicks');
27
28 my $cgi = new CGI;
29 my $uri = $cgi->param('uri') || '';
30
31 if ($uri) {
32     if ( $trackinglinks eq 'track' || $trackinglinks eq 'anonymous' ) {
33         my $borrowernumber = 0;
34
35         # we have a uri and we want to track
36         if ( $trackinglinks eq 'track' ) {
37             my ( $user, $cookie, $sessionID, $flags ) =
38               checkauth( $cgi, 1, '', 'opac' );
39             my $userenv = C4::Context->userenv;
40
41             if (   defined($userenv)
42                 && ref($userenv) eq 'HASH'
43                 && $userenv->{number} )
44             {
45                 $borrowernumber = $userenv->{number};
46             }
47
48             # get borrower info
49         }
50         my $biblionumber = $cgi->param('biblionumber') || 0;
51         my $itemnumber   = $cgi->param('itemnumber')   || 0;
52
53         trackclick( $uri, $biblionumber, $borrowernumber, $itemnumber );
54         print $cgi->redirect($uri);
55     }
56     else {
57
58         # We have a valid url, but we shouldn't track it, just redirect
59         print $cgi->redirect($uri);
60     }
61 }
62 else {
63
64     # we shouldn't be here, bail out
65     print $cgi->redirect("/cgi-bin/koha/errors/404.pl");    # escape early
66     exit;
67 }
68
69 sub trackclick {
70     my ( $uri, $biblionumber, $borrowernumber, $itemnumber ) = @_;
71     my $dbh   = C4::Context->dbh();
72     my $query = "INSERT INTO linktracker (biblionumber,itemnumber,borrowernumber
73     ,url,timeclicked) VALUES (?,?,?,?,now())";
74     my $sth = $dbh->prepare($query);
75     $sth->execute( $biblionumber, $itemnumber, $borrowernumber, $uri );
76
77 }