Bug 12760 - add restrictions purge to cleanup_database.pl (followup 2)
[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 Modern::Perl;
21
22 use constant DEFAULT_ZEBRAQ_PURGEDAYS             => 30;
23 use constant DEFAULT_MAIL_PURGEDAYS               => 30;
24 use constant DEFAULT_IMPORT_PURGEDAYS             => 60;
25 use constant DEFAULT_LOGS_PURGEDAYS               => 180;
26 use constant DEFAULT_SEARCHHISTORY_PURGEDAYS      => 30;
27 use constant DEFAULT_SHARE_INVITATION_EXPIRY_DAYS => 14;
28 use constant DEFAULT_DEBARMENTS_PURGEDAYS         => 30;
29
30 BEGIN {
31     # find Koha's Perl modules
32     # test carefully before changing this
33     use FindBin;
34     eval { require "$FindBin::Bin/../kohalib.pl" };
35 }
36
37 use C4::Context;
38 use C4::Dates;
39
40 use C4::Search;
41
42 use Getopt::Long;
43
44 sub usage {
45     print STDERR <<USAGE;
46 Usage: $0 [-h|--help] [--sessions] [--sessdays DAYS] [-v|--verbose] [--zebraqueue DAYS] [-m|--mail] [--merged] [--import DAYS] [--logs DAYS] [--searchhistory DAYS] [--restrictions DAYS]
47
48    -h --help          prints this help message, and exits, ignoring all
49                       other options
50    --sessions         purge the sessions table.  If you use this while users 
51                       are logged into Koha, they will have to reconnect.
52    --sessdays DAYS    purge only sessions older than DAYS days.
53    -v --verbose       will cause the script to give you a bit more information
54                       about the run.
55    --zebraqueue DAYS  purge completed zebraqueue entries older than DAYS days.
56                       Defaults to 30 days if no days specified.
57    -m --mail DAYS     purge items from the mail queue that are older than DAYS days.
58                       Defaults to 30 days if no days specified.
59    --merged           purged completed entries from need_merge_authorities.
60    --import DAYS      purge records from import tables older than DAYS days.
61                       Defaults to 60 days if no days specified.
62    --z3950            purge records from import tables that are the result
63                       of Z39.50 searches
64    --logs DAYS        purge entries from action_logs older than DAYS days.
65                       Defaults to 180 days if no days specified.
66    --searchhistory DAYS  purge entries from search_history older than DAYS days.
67                          Defaults to 30 days if no days specified
68    --list-invites  DAYS  purge (unaccepted) list share invites older than DAYS
69                          days.  Defaults to 14 days if no days specified.
70    --restrictions DAYS   purge patrons restrictions expired since more than DAYS days.
71                          Defaults to 30 days if no days specified.
72 USAGE
73     exit $_[0];
74 }
75
76 my (
77     $help,   $sessions,          $sess_days, $verbose, $zebraqueue_days,
78     $mail,   $purge_merged,      $pImport,   $pLogs,   $pSearchhistory,
79     $pZ3950, $pListShareInvites, $pDebarments,
80 );
81
82 GetOptions(
83     'h|help'          => \$help,
84     'sessions'        => \$sessions,
85     'sessdays:i'      => \$sess_days,
86     'v|verbose'       => \$verbose,
87     'm|mail:i'        => \$mail,
88     'zebraqueue:i'    => \$zebraqueue_days,
89     'merged'          => \$purge_merged,
90     'import:i'        => \$pImport,
91     'z3950'           => \$pZ3950,
92     'logs:i'          => \$pLogs,
93     'searchhistory:i' => \$pSearchhistory,
94     'list-invites:i'  => \$pListShareInvites,
95     'restrictions:i'  => \$pDebarments,
96 ) || usage(1);
97
98 # Use default values
99 $sessions          = 1                                    if $sess_days                  && $sess_days > 0;
100 $pImport           = DEFAULT_IMPORT_PURGEDAYS             if defined($pImport)           && $pImport == 0;
101 $pLogs             = DEFAULT_LOGS_PURGEDAYS               if defined($pLogs)             && $pLogs == 0;
102 $zebraqueue_days   = DEFAULT_ZEBRAQ_PURGEDAYS             if defined($zebraqueue_days)   && $zebraqueue_days == 0;
103 $mail              = DEFAULT_MAIL_PURGEDAYS               if defined($mail)              && $mail == 0;
104 $pSearchhistory    = DEFAULT_SEARCHHISTORY_PURGEDAYS      if defined($pSearchhistory)    && $pSearchhistory == 0;
105 $pListShareInvites = DEFAULT_SHARE_INVITATION_EXPIRY_DAYS if defined($pListShareInvites) && $pListShareInvites == 0;
106 $pDebarments       = DEFAULT_DEBARMENTS_PURGEDAYS         if defined($pDebarments)       && $pDebarments == 0;
107
108 if ($help) {
109     usage(0);
110 }
111
112 unless ( $sessions
113     || $zebraqueue_days
114     || $mail
115     || $purge_merged
116     || $pImport
117     || $pLogs
118     || $pSearchhistory
119     || $pZ3950
120     || $pListShareInvites
121     || $pDebarments )
122 {
123     print "You did not specify any cleanup work for the script to do.\n\n";
124     usage(1);
125 }
126
127 my $dbh = C4::Context->dbh();
128 my $sth;
129 my $sth2;
130 my $count;
131
132 if ( $sessions && !$sess_days ) {
133     if ($verbose) {
134         print "Session purge triggered.\n";
135         $sth = $dbh->prepare(q{ SELECT COUNT(*) FROM sessions });
136         $sth->execute() or die $dbh->errstr;
137         my @count_arr = $sth->fetchrow_array;
138         print "$count_arr[0] entries will be deleted.\n";
139     }
140     $sth = $dbh->prepare(q{ TRUNCATE sessions });
141     $sth->execute() or die $dbh->errstr;
142     if ($verbose) {
143         print "Done with session purge.\n";
144     }
145 }
146 elsif ( $sessions && $sess_days > 0 ) {
147     print "Session purge triggered with days>$sess_days.\n" if $verbose;
148     RemoveOldSessions();
149     print "Done with session purge with days>$sess_days.\n" if $verbose;
150 }
151
152 if ($zebraqueue_days) {
153     $count = 0;
154     print "Zebraqueue purge triggered for $zebraqueue_days days.\n" if $verbose;
155     $sth = $dbh->prepare(
156         q{
157             SELECT id,biblio_auth_number,server,time
158             FROM zebraqueue
159             WHERE done=1 AND time < date_sub(curdate(), INTERVAL ? DAY)
160         }
161     );
162     $sth->execute($zebraqueue_days) or die $dbh->errstr;
163     $sth2 = $dbh->prepare(q{ DELETE FROM zebraqueue WHERE id=? });
164     while ( my $record = $sth->fetchrow_hashref ) {
165         $sth2->execute( $record->{id} ) or die $dbh->errstr;
166         $count++;
167     }
168     print "$count records were deleted.\nDone with zebraqueue purge.\n" if $verbose;
169 }
170
171 if ($mail) {
172     print "Mail queue purge triggered for $mail days.\n" if $verbose;
173     $sth = $dbh->prepare(
174         q{
175             DELETE FROM message_queue
176             WHERE time_queued < date_sub(curdate(), INTERVAL ? DAY)
177         }
178     );
179     $sth->execute($mail) or die $dbh->errstr;
180     $count = $sth->rows;
181     $sth->finish;
182     print "$count messages were deleted from the mail queue.\nDone with message_queue purge.\n" if $verbose;
183 }
184
185 if ($purge_merged) {
186     print "Purging completed entries from need_merge_authorities.\n" if $verbose;
187     $sth = $dbh->prepare(q{ DELETE FROM need_merge_authorities WHERE done=1 });
188     $sth->execute() or die $dbh->errstr;
189     print "Done with purging need_merge_authorities.\n" if $verbose;
190 }
191
192 if ($pImport) {
193     print "Purging records from import tables.\n" if $verbose;
194     PurgeImportTables();
195     print "Done with purging import tables.\n" if $verbose;
196 }
197
198 if ($pZ3950) {
199     print "Purging Z39.50 records from import tables.\n" if $verbose;
200     PurgeZ3950();
201     print "Done with purging Z39.50 records from import tables.\n" if $verbose;
202 }
203
204 if ($pLogs) {
205     print "Purging records from action_logs.\n" if $verbose;
206     $sth = $dbh->prepare(
207         q{
208             DELETE FROM action_logs
209             WHERE timestamp < date_sub(curdate(), INTERVAL ? DAY)
210         }
211     );
212     $sth->execute($pLogs) or die $dbh->errstr;
213     print "Done with purging action_logs.\n" if $verbose;
214 }
215
216 if ($pSearchhistory) {
217     print "Purging records older than $pSearchhistory from search_history.\n" if $verbose;
218     PurgeSearchHistory($pSearchhistory);
219     print "Done with purging search_history.\n" if $verbose;
220 }
221
222 if ($pListShareInvites) {
223     print "Purging unaccepted list share invites older than $pListShareInvites days.\n" if $verbose;
224     $sth = $dbh->prepare(
225         q{
226             DELETE FROM virtualshelfshares
227             WHERE invitekey IS NOT NULL
228             AND (sharedate + INTERVAL ? DAY) < NOW()
229         }
230     );
231     $sth->execute($pListShareInvites);
232     print "Done with purging unaccepted list share invites.\n" if $verbose;
233 }
234
235 if ($pDebarments) {
236     print "Expired patrons restrictions purge triggered for $pDebarments days.\n" if $verbose;
237     $count = PurgeDebarments();
238     print "$count restrictions were deleted.\nDone with restrictions purge.\n" if $verbose;
239 }
240
241 exit(0);
242
243 sub RemoveOldSessions {
244     my ( $id, $a_session, $limit, $lasttime );
245     $limit = time() - 24 * 3600 * $sess_days;
246
247     $sth = $dbh->prepare(q{ SELECT id, a_session FROM sessions });
248     $sth->execute or die $dbh->errstr;
249     $sth->bind_columns( \$id, \$a_session );
250     $sth2  = $dbh->prepare(q{ DELETE FROM sessions WHERE id=? });
251     $count = 0;
252
253     while ( $sth->fetch ) {
254         $lasttime = 0;
255         if ( $a_session =~ /lasttime:\s+'?(\d+)/ ) {
256             $lasttime = $1;
257         }
258         elsif ( $a_session =~ /(ATIME|CTIME):\s+'?(\d+)/ ) {
259             $lasttime = $2;
260         }
261         if ( $lasttime && $lasttime < $limit ) {
262             $sth2->execute($id) or die $dbh->errstr;
263             $count++;
264         }
265     }
266     if ($verbose) {
267         print "$count sessions were deleted.\n";
268     }
269 }
270
271 sub PurgeImportTables {
272
273     #First purge import_records
274     #Delete cascades to import_biblios, import_items and import_record_matches
275     $sth = $dbh->prepare(
276         q{
277             DELETE FROM import_records
278             WHERE upload_timestamp < date_sub(curdate(), INTERVAL ? DAY)
279         }
280     );
281     $sth->execute($pImport) or die $dbh->errstr;
282
283     # Now purge import_batches
284     # Timestamp cannot be used here without care, because records are added
285     # continuously to batches without updating timestamp (Z39.50 search).
286     # So we only delete older empty batches.
287     # This delete will therefore not have a cascading effect.
288     $sth = $dbh->prepare(
289         q{
290             DELETE ba
291             FROM import_batches ba
292             LEFT JOIN import_records re ON re.import_batch_id=ba.import_batch_id
293             WHERE re.import_record_id IS NULL AND
294             ba.upload_timestamp < date_sub(curdate(), INTERVAL ? DAY)
295         }
296     );
297     $sth->execute($pImport) or die $dbh->errstr;
298 }
299
300 sub PurgeZ3950 {
301     $sth = $dbh->prepare(
302         q{
303             DELETE FROM import_batches
304             WHERE batch_type = 'z3950'
305         }
306     );
307     $sth->execute() or die $dbh->errstr;
308 }
309
310 sub PurgeDebarments {
311     require Koha::Borrower::Debarments;
312     $count = 0;
313     $sth   = $dbh->prepare(
314         q{
315             SELECT borrower_debarment_id
316             FROM borrower_debarments
317             WHERE expiration < date_sub(curdate(), INTERVAL ? DAY)
318         }
319     );
320     $sth->execute($pDebarments) or die $dbh->errstr;
321     while ( my ($borrower_debarment_id) = $sth->fetchrow_array ) {
322         Koha::Borrower::Debarments::DelDebarment($borrower_debarment_id);
323         $count++;
324     }
325     return $count;
326 }