Bug 14960: Remove C4::Dates from files in misc/cronjobs
[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
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
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::Search;
39 use C4::Search::History;
40 use Getopt::Long;
41 use C4::Log;
42 use C4::Accounts;
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] [--all-restrictions] [--fees 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    --fees DAYS        purge entries accountlines older than DAYS days, where
65                       amountoutstanding is 0 or NULL.
66                       In the case of --feees, DAYS must be greater than
67                       or equal to 1.
68                       WARNING: Fees and payments may not be deleted together.
69                       This will not affect the account balance but may be
70                       confusing to staff.
71    --logs DAYS        purge entries from action_logs older than DAYS days.
72                       Defaults to 180 days if no days specified.
73    --searchhistory DAYS  purge entries from search_history older than DAYS days.
74                          Defaults to 30 days if no days specified
75    --list-invites  DAYS  purge (unaccepted) list share invites older than DAYS
76                          days.  Defaults to 14 days if no days specified.
77    --restrictions DAYS   purge patrons restrictions expired since more than DAYS days.
78                          Defaults to 30 days if no days specified.
79     --all-restrictions   purge all expired patrons restrictions.
80    --del-exp-selfreg  Delete expired self registration accounts
81    --del-unv-selfreg DAYS  Delete unverified self registrations older than DAYS
82 USAGE
83     exit $_[0];
84 }
85
86 my $help;
87 my $sessions;
88 my $sess_days;
89 my $verbose;
90 my $zebraqueue_days;
91 my $mail;
92 my $purge_merged;
93 my $pImport;
94 my $pLogs;
95 my $pSearchhistory;
96 my $pZ3950;
97 my $pListShareInvites;
98 my $pDebarments;
99 my $allDebarments;
100 my $pExpSelfReg;
101 my $pUnvSelfReg;
102 my $fees_days;
103
104 GetOptions(
105     'h|help'          => \$help,
106     'sessions'        => \$sessions,
107     'sessdays:i'      => \$sess_days,
108     'v|verbose'       => \$verbose,
109     'm|mail:i'        => \$mail,
110     'zebraqueue:i'    => \$zebraqueue_days,
111     'merged'          => \$purge_merged,
112     'import:i'        => \$pImport,
113     'z3950'           => \$pZ3950,
114     'logs:i'          => \$pLogs,
115     'fees:i'          => \$fees_days,
116     'searchhistory:i' => \$pSearchhistory,
117     'list-invites:i'  => \$pListShareInvites,
118     'restrictions:i'  => \$pDebarments,
119     'all-restrictions' => \$allDebarments,
120     'del-exp-selfreg' => \$pExpSelfReg,
121     'del-unv-selfreg' => \$pUnvSelfReg,
122 ) || usage(1);
123
124 # Use default values
125 $sessions          = 1                                    if $sess_days                  && $sess_days > 0;
126 $pImport           = DEFAULT_IMPORT_PURGEDAYS             if defined($pImport)           && $pImport == 0;
127 $pLogs             = DEFAULT_LOGS_PURGEDAYS               if defined($pLogs)             && $pLogs == 0;
128 $zebraqueue_days   = DEFAULT_ZEBRAQ_PURGEDAYS             if defined($zebraqueue_days)   && $zebraqueue_days == 0;
129 $mail              = DEFAULT_MAIL_PURGEDAYS               if defined($mail)              && $mail == 0;
130 $pSearchhistory    = DEFAULT_SEARCHHISTORY_PURGEDAYS      if defined($pSearchhistory)    && $pSearchhistory == 0;
131 $pListShareInvites = DEFAULT_SHARE_INVITATION_EXPIRY_DAYS if defined($pListShareInvites) && $pListShareInvites == 0;
132 $pDebarments       = DEFAULT_DEBARMENTS_PURGEDAYS         if defined($pDebarments)       && $pDebarments == 0;
133
134 if ($help) {
135     usage(0);
136 }
137
138 unless ( $sessions
139     || $zebraqueue_days
140     || $mail
141     || $purge_merged
142     || $pImport
143     || $pLogs
144     || $fees_days
145     || $pSearchhistory
146     || $pZ3950
147     || $pListShareInvites
148     || $pDebarments
149     || $allDebarments
150     || $pExpSelfReg
151     || $pUnvSelfReg
152 ) {
153     print "You did not specify any cleanup work for the script to do.\n\n";
154     usage(1);
155 }
156
157 if ($pDebarments && $allDebarments) {
158     print "You can not specify both --restrictions and --all-restrictions.\n\n";
159     usage(1);
160 }
161
162 cronlogaction();
163
164 my $dbh = C4::Context->dbh();
165 my $sth;
166 my $sth2;
167 my $count;
168
169 if ( $sessions && !$sess_days ) {
170     if ($verbose) {
171         print "Session purge triggered.\n";
172         $sth = $dbh->prepare(q{ SELECT COUNT(*) FROM sessions });
173         $sth->execute() or die $dbh->errstr;
174         my @count_arr = $sth->fetchrow_array;
175         print "$count_arr[0] entries will be deleted.\n";
176     }
177     $sth = $dbh->prepare(q{ TRUNCATE sessions });
178     $sth->execute() or die $dbh->errstr;
179     if ($verbose) {
180         print "Done with session purge.\n";
181     }
182 }
183 elsif ( $sessions && $sess_days > 0 ) {
184     print "Session purge triggered with days>$sess_days.\n" if $verbose;
185     RemoveOldSessions();
186     print "Done with session purge with days>$sess_days.\n" if $verbose;
187 }
188
189 if ($zebraqueue_days) {
190     $count = 0;
191     print "Zebraqueue purge triggered for $zebraqueue_days days.\n" if $verbose;
192     $sth = $dbh->prepare(
193         q{
194             SELECT id,biblio_auth_number,server,time
195             FROM zebraqueue
196             WHERE done=1 AND time < date_sub(curdate(), INTERVAL ? DAY)
197         }
198     );
199     $sth->execute($zebraqueue_days) or die $dbh->errstr;
200     $sth2 = $dbh->prepare(q{ DELETE FROM zebraqueue WHERE id=? });
201     while ( my $record = $sth->fetchrow_hashref ) {
202         $sth2->execute( $record->{id} ) or die $dbh->errstr;
203         $count++;
204     }
205     print "$count records were deleted.\nDone with zebraqueue purge.\n" if $verbose;
206 }
207
208 if ($mail) {
209     print "Mail queue purge triggered for $mail days.\n" if $verbose;
210     $sth = $dbh->prepare(
211         q{
212             DELETE FROM message_queue
213             WHERE time_queued < date_sub(curdate(), INTERVAL ? DAY)
214         }
215     );
216     $sth->execute($mail) or die $dbh->errstr;
217     $count = $sth->rows;
218     $sth->finish;
219     print "$count messages were deleted from the mail queue.\nDone with message_queue purge.\n" if $verbose;
220 }
221
222 if ($purge_merged) {
223     print "Purging completed entries from need_merge_authorities.\n" if $verbose;
224     $sth = $dbh->prepare(q{ DELETE FROM need_merge_authorities WHERE done=1 });
225     $sth->execute() or die $dbh->errstr;
226     print "Done with purging need_merge_authorities.\n" if $verbose;
227 }
228
229 if ($pImport) {
230     print "Purging records from import tables.\n" if $verbose;
231     PurgeImportTables();
232     print "Done with purging import tables.\n" if $verbose;
233 }
234
235 if ($pZ3950) {
236     print "Purging Z39.50 records from import tables.\n" if $verbose;
237     PurgeZ3950();
238     print "Done with purging Z39.50 records from import tables.\n" if $verbose;
239 }
240
241 if ($pLogs) {
242     print "Purging records from action_logs.\n" if $verbose;
243     $sth = $dbh->prepare(
244         q{
245             DELETE FROM action_logs
246             WHERE timestamp < date_sub(curdate(), INTERVAL ? DAY)
247         }
248     );
249     $sth->execute($pLogs) or die $dbh->errstr;
250     print "Done with purging action_logs.\n" if $verbose;
251 }
252
253 if ($fees_days) {
254     print "Purging records from accountlines.\n" if $verbose;
255     purge_zero_balance_fees( $fees_days );
256     print "Done purging records from accountlines.\n" if $verbose;
257 }
258
259 if ($pSearchhistory) {
260     print "Purging records older than $pSearchhistory from search_history.\n" if $verbose;
261     C4::Search::History::delete({ interval => $pSearchhistory });
262     print "Done with purging search_history.\n" if $verbose;
263 }
264
265 if ($pListShareInvites) {
266     print "Purging unaccepted list share invites older than $pListShareInvites days.\n" if $verbose;
267     $sth = $dbh->prepare(
268         q{
269             DELETE FROM virtualshelfshares
270             WHERE invitekey IS NOT NULL
271             AND (sharedate + INTERVAL ? DAY) < NOW()
272         }
273     );
274     $sth->execute($pListShareInvites);
275     print "Done with purging unaccepted list share invites.\n" if $verbose;
276 }
277
278 if ($pDebarments) {
279     print "Expired patrons restrictions purge triggered for $pDebarments days.\n" if $verbose;
280     $count = PurgeDebarments($pDebarments);
281     print "$count restrictions were deleted.\nDone with restrictions purge.\n" if $verbose;
282 }
283
284 if($allDebarments) {
285     print "All expired patrons restrictions purge triggered.\n" if $verbose;
286     $count = PurgeDebarments(0);
287     print "$count restrictions were deleted.\nDone with all restrictions purge.\n" if $verbose;
288 }
289
290 if( $pExpSelfReg ) {
291     DeleteExpiredSelfRegs();
292 }
293 if( $pUnvSelfReg ) {
294     DeleteUnverifiedSelfRegs( $pUnvSelfReg );
295 }
296
297 exit(0);
298
299 sub RemoveOldSessions {
300     my ( $id, $a_session, $limit, $lasttime );
301     $limit = time() - 24 * 3600 * $sess_days;
302
303     $sth = $dbh->prepare(q{ SELECT id, a_session FROM sessions });
304     $sth->execute or die $dbh->errstr;
305     $sth->bind_columns( \$id, \$a_session );
306     $sth2  = $dbh->prepare(q{ DELETE FROM sessions WHERE id=? });
307     $count = 0;
308
309     while ( $sth->fetch ) {
310         $lasttime = 0;
311         if ( $a_session =~ /lasttime:\s+'?(\d+)/ ) {
312             $lasttime = $1;
313         }
314         elsif ( $a_session =~ /(ATIME|CTIME):\s+'?(\d+)/ ) {
315             $lasttime = $2;
316         }
317         if ( $lasttime && $lasttime < $limit ) {
318             $sth2->execute($id) or die $dbh->errstr;
319             $count++;
320         }
321     }
322     if ($verbose) {
323         print "$count sessions were deleted.\n";
324     }
325 }
326
327 sub PurgeImportTables {
328
329     #First purge import_records
330     #Delete cascades to import_biblios, import_items and import_record_matches
331     $sth = $dbh->prepare(
332         q{
333             DELETE FROM import_records
334             WHERE upload_timestamp < date_sub(curdate(), INTERVAL ? DAY)
335         }
336     );
337     $sth->execute($pImport) or die $dbh->errstr;
338
339     # Now purge import_batches
340     # Timestamp cannot be used here without care, because records are added
341     # continuously to batches without updating timestamp (Z39.50 search).
342     # So we only delete older empty batches.
343     # This delete will therefore not have a cascading effect.
344     $sth = $dbh->prepare(
345         q{
346             DELETE ba
347             FROM import_batches ba
348             LEFT JOIN import_records re ON re.import_batch_id=ba.import_batch_id
349             WHERE re.import_record_id IS NULL AND
350             ba.upload_timestamp < date_sub(curdate(), INTERVAL ? DAY)
351         }
352     );
353     $sth->execute($pImport) or die $dbh->errstr;
354 }
355
356 sub PurgeZ3950 {
357     $sth = $dbh->prepare(
358         q{
359             DELETE FROM import_batches
360             WHERE batch_type = 'z3950'
361         }
362     );
363     $sth->execute() or die $dbh->errstr;
364 }
365
366 sub PurgeDebarments {
367     require Koha::Borrower::Debarments;
368     my $days = shift;
369     $count = 0;
370     $sth   = $dbh->prepare(
371         q{
372             SELECT borrower_debarment_id
373             FROM borrower_debarments
374             WHERE expiration < date_sub(curdate(), INTERVAL ? DAY)
375         }
376     );
377     $sth->execute($days) or die $dbh->errstr;
378     while ( my ($borrower_debarment_id) = $sth->fetchrow_array ) {
379         Koha::Borrower::Debarments::DelDebarment($borrower_debarment_id);
380         $count++;
381     }
382     return $count;
383 }
384
385 sub DeleteExpiredSelfRegs {
386     my $cnt= C4::Members::DeleteExpiredOpacRegistrations();
387     print "Removed $cnt expired self-registered borrowers\n" if $verbose;
388 }
389
390 sub DeleteUnverifiedSelfRegs {
391     my $cnt= C4::Members::DeleteUnverifiedOpacRegistrations( $_[0] );
392     print "Removed $cnt unverified self-registrations\n" if $verbose;
393 }