Merge remote-tracking branch 'origin/new/bug_5533'
[koha.git] / misc / cronjobs / cleanup_database.pl
1 #!/usr/bin/perl
2
3 # Copyright 2009 PTFS, Inc.
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along
17 # with Koha; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19
20 use strict;
21 use warnings;
22
23 use constant DEFAULT_ZEBRAQ_PURGEDAYS => 30;
24 use constant DEFAULT_IMPORT_PURGEDAYS => 60;
25 use constant DEFAULT_LOGS_PURGEDAYS => 180;
26
27 BEGIN {
28     # find Koha's Perl modules
29     # test carefully before changing this
30     use FindBin;
31     eval { require "$FindBin::Bin/../kohalib.pl" };
32 }
33
34 use C4::Context;
35 use C4::Dates;
36
37 use Getopt::Long;
38
39 sub usage {
40     print STDERR <<USAGE;
41 Usage: $0 [-h|--help] [--sessions] [--sessdays DAYS] [-v|--verbose] [--zebraqueue DAYS] [-m|--mail] [--merged] [--import DAYS] [--logs DAYS]
42
43    -h --help          prints this help message, and exits, ignoring all
44                       other options
45    --sessions         purge the sessions table.  If you use this while users 
46                       are logged into Koha, they will have to reconnect.
47    --sessdays DAYS    purge only sessions older than DAYS days.
48    -v --verbose       will cause the script to give you a bit more information
49                       about the run.
50    --zebraqueue DAYS  purge completed zebraqueue entries older than DAYS days.
51                       Defaults to 30 days if no days specified.
52    -m --mail          purge the mail queue. 
53    --merged           purged completed entries from need_merge_authorities.
54    --import DAYS      purge records from import tables older than DAYS days.
55                       Defaults to 60 days if no days specified.
56    --logs DAYS        purge entries from action_logs older than DAYS days.
57                       Defaults to 180 days if no days specified.
58 USAGE
59     exit $_[0];
60 }
61
62 my ( $help, $sessions, $sess_days, $verbose, $zebraqueue_days, $mail, $purge_merged, $pImport, $pLogs);
63
64 GetOptions(
65     'h|help'       => \$help,
66     'sessions'     => \$sessions,
67     'sessdays:i'   => \$sess_days,
68     'v|verbose'    => \$verbose,
69     'm|mail'       => \$mail,
70     'zebraqueue:i' => \$zebraqueue_days,
71     'merged'       => \$purge_merged,
72     'import:i'     => \$pImport,
73     'logs:i'       => \$pLogs,
74 ) || usage(1);
75
76 $sessions=1 if $sess_days && $sess_days>0;
77 # if --import, --logs or --zebraqueue were passed without number of days,
78 # use defaults
79 $pImport= DEFAULT_IMPORT_PURGEDAYS if defined($pImport) && $pImport==0;
80 $pLogs= DEFAULT_LOGS_PURGEDAYS if defined($pLogs) && $pLogs==0;
81 $zebraqueue_days= DEFAULT_ZEBRAQ_PURGEDAYS if defined($zebraqueue_days) && $zebraqueue_days==0;
82
83 if ($help) {
84     usage(0);
85 }
86
87 if ( !( $sessions || $zebraqueue_days || $mail || $purge_merged || $pImport || $pLogs) ) {
88     print "You did not specify any cleanup work for the script to do.\n\n";
89     usage(1);
90 }
91
92 my $dbh = C4::Context->dbh();
93 my $query;
94 my $sth;
95 my $sth2;
96 my $count;
97
98 if ( $sessions && !$sess_days ) {
99     if ($verbose) {
100         print "Session purge triggered.\n";
101         $sth = $dbh->prepare("SELECT COUNT(*) FROM sessions");
102         $sth->execute() or die $dbh->errstr;
103         my @count_arr = $sth->fetchrow_array;
104         print "$count_arr[0] entries will be deleted.\n";
105     }
106     $sth = $dbh->prepare("TRUNCATE sessions");
107     $sth->execute() or die $dbh->errstr;
108     if ($verbose) {
109         print "Done with session purge.\n";
110     }
111 } elsif ( $sessions && $sess_days > 0 ) {
112     if ($verbose) {
113         print "Session purge triggered with days>$sess_days.\n";
114     }
115     RemoveOldSessions();
116     if ($verbose) {
117         print "Done with session purge with days>$sess_days.\n";
118     }
119 }
120
121 if ($zebraqueue_days) {
122     $count = 0;
123     if ($verbose) {
124         print "Zebraqueue purge triggered for $zebraqueue_days days.\n";
125     }
126     $sth = $dbh->prepare(
127         "SELECT id,biblio_auth_number,server,time FROM zebraqueue
128                           WHERE done=1 and time < date_sub(curdate(), interval ? day)"
129     );
130     $sth->execute($zebraqueue_days) or die $dbh->errstr;
131     $sth2 = $dbh->prepare("DELETE FROM zebraqueue WHERE id=?");
132     while ( my $record = $sth->fetchrow_hashref ) {
133         $sth2->execute( $record->{id} ) or die $dbh->errstr;
134         $count++;
135     }
136     if ($verbose) {
137         print "$count records were deleted.\nDone with zebraqueue purge.\n";
138     }
139 }
140
141 if ($mail) {
142     if ($verbose) {
143         $sth = $dbh->prepare("SELECT COUNT(*) FROM message_queue");
144         $sth->execute() or die $dbh->errstr;
145         my @count_arr = $sth->fetchrow_array;
146         print "Deleting $count_arr[0] entries from the mail queue.\n";
147     }
148     $sth = $dbh->prepare("TRUNCATE message_queue");
149     $sth->execute() or $dbh->errstr;
150     print "Done with purging the mail queue.\n" if ($verbose);
151 }
152
153 if($purge_merged) {
154     print "Purging completed entries from need_merge_authorities.\n" if $verbose;
155     $sth = $dbh->prepare("DELETE FROM need_merge_authorities WHERE done=1");
156     $sth->execute() or die $dbh->errstr;
157     print "Done with purging need_merge_authorities.\n" if $verbose;
158 }
159
160 if($pImport) {
161     print "Purging records from import tables.\n" if $verbose;
162     PurgeImportTables();
163     print "Done with purging import tables.\n" if $verbose;
164 }
165
166 if($pLogs) {
167     print "Purging records from action_logs.\n" if $verbose;
168     $sth = $dbh->prepare("DELETE FROM action_logs WHERE timestamp < date_sub(curdate(), interval ? DAY)");
169     $sth->execute($pLogs) or die $dbh->errstr;
170     print "Done with purging action_logs.\n" if $verbose;
171 }
172
173 exit(0);
174
175 sub RemoveOldSessions {
176     my ( $id, $a_session, $limit, $lasttime );
177     $limit = time() - 24 * 3600 * $sess_days;
178
179     $sth = $dbh->prepare("SELECT id, a_session FROM sessions");
180     $sth->execute or die $dbh->errstr;
181     $sth->bind_columns( \$id, \$a_session );
182     $sth2  = $dbh->prepare("DELETE FROM sessions WHERE id=?");
183     $count = 0;
184
185     while ( $sth->fetch ) {
186         $lasttime = 0;
187         if ( $a_session =~ /lasttime:\s+'?(\d+)/ ) {
188             $lasttime = $1;
189         } elsif ( $a_session =~ /(ATIME|CTIME):\s+'?(\d+)/ ) {
190             $lasttime = $2;
191         }
192         if ( $lasttime && $lasttime < $limit ) {
193             $sth2->execute($id) or die $dbh->errstr;
194             $count++;
195         }
196     }
197     if ($verbose) {
198         print "$count sessions were deleted.\n";
199     }
200 }
201
202 sub PurgeImportTables {
203     #First purge import_records
204     #Delete cascades to import_biblios, import_items and import_record_matches
205     $sth = $dbh->prepare("DELETE FROM import_records WHERE upload_timestamp < date_sub(curdate(), interval ? DAY)");
206     $sth->execute($pImport) or die $dbh->errstr;
207
208     # Now purge import_batches
209     # Timestamp cannot be used here without care, because records are added
210     # continuously to batches without updating timestamp (z3950 search).
211     # So we only delete older empty batches.
212     # This delete will therefore not have a cascading effect.
213     $sth = $dbh->prepare("DELETE ba
214  FROM import_batches ba
215  LEFT JOIN import_records re ON re.import_batch_id=ba.import_batch_id
216  WHERE re.import_record_id IS NULL AND
217  ba.upload_timestamp < date_sub(curdate(), interval ? DAY)");
218     $sth->execute($pImport) or die $dbh->errstr;
219 }