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