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