Bug 19008: More database cleanups - statistics
[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 Koha::Script -cron;
38 use C4::Context;
39 use C4::Search;
40 use C4::Search::History;
41 use Getopt::Long;
42 use C4::Log;
43 use C4::Accounts;
44 use Koha::UploadedFiles;
45
46 sub usage {
47     print STDERR <<USAGE;
48 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] [--temp-uploads] [--temp-uploads-days DAYS] [--uploads-missing 0|1 ] [--statistics DAYS]
49
50    -h --help          prints this help message, and exits, ignoring all
51                       other options
52    --sessions         purge the sessions table.  If you use this while users 
53                       are logged into Koha, they will have to reconnect.
54    --sessdays DAYS    purge only sessions older than DAYS days.
55    -v --verbose       will cause the script to give you a bit more information
56                       about the run.
57    --zebraqueue DAYS  purge completed zebraqueue entries older than DAYS days.
58                       Defaults to 30 days if no days specified.
59    -m --mail DAYS     purge items from the mail queue that are older than DAYS days.
60                       Defaults to 30 days if no days specified.
61    --merged           purged completed entries from need_merge_authorities.
62    --import DAYS      purge records from import tables older than DAYS days.
63                       Defaults to 60 days if no days specified.
64    --z3950            purge records from import tables that are the result
65                       of Z39.50 searches
66    --fees DAYS        purge entries accountlines older than DAYS days, where
67                       amountoutstanding is 0 or NULL.
68                       In the case of --fees, DAYS must be greater than
69                       or equal to 1.
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    --unique-holidays DAYS  Delete all unique holidays older than DAYS
82    --temp-uploads     Delete temporary uploads.
83    --temp-uploads-days DAYS Override the corresponding preference value.
84    --uploads-missing FLAG Delete upload records for missing files when FLAG is true, count them otherwise
85    --oauth-tokens     Delete expired OAuth2 tokens
86    --statistics DAYS       Purge entries from statistics older than DAYS days.
87 USAGE
88     exit $_[0];
89 }
90
91 my $help;
92 my $sessions;
93 my $sess_days;
94 my $verbose;
95 my $zebraqueue_days;
96 my $mail;
97 my $purge_merged;
98 my $pImport;
99 my $pLogs;
100 my $pSearchhistory;
101 my $pZ3950;
102 my $pListShareInvites;
103 my $pDebarments;
104 my $allDebarments;
105 my $pExpSelfReg;
106 my $pUnvSelfReg;
107 my $fees_days;
108 my $special_holidays_days;
109 my $temp_uploads;
110 my $temp_uploads_days;
111 my $uploads_missing;
112 my $oauth_tokens;
113 my $pStatistics;
114
115 GetOptions(
116     'h|help'            => \$help,
117     'sessions'          => \$sessions,
118     'sessdays:i'        => \$sess_days,
119     'v|verbose'         => \$verbose,
120     'm|mail:i'          => \$mail,
121     'zebraqueue:i'      => \$zebraqueue_days,
122     'merged'            => \$purge_merged,
123     'import:i'          => \$pImport,
124     'z3950'             => \$pZ3950,
125     'logs:i'            => \$pLogs,
126     'fees:i'            => \$fees_days,
127     'searchhistory:i'   => \$pSearchhistory,
128     'list-invites:i'    => \$pListShareInvites,
129     'restrictions:i'    => \$pDebarments,
130     'all-restrictions'  => \$allDebarments,
131     'del-exp-selfreg'   => \$pExpSelfReg,
132     'del-unv-selfreg'   => \$pUnvSelfReg,
133     'unique-holidays:i' => \$special_holidays_days,
134     'temp-uploads'      => \$temp_uploads,
135     'temp-uploads-days:i' => \$temp_uploads_days,
136     'uploads-missing:i' => \$uploads_missing,
137     'oauth-tokens'      => \$oauth_tokens,
138     'statistics:i'      => \$pStatistics,
139 ) || usage(1);
140
141 # Use default values
142 $sessions          = 1                                    if $sess_days                  && $sess_days > 0;
143 $pImport           = DEFAULT_IMPORT_PURGEDAYS             if defined($pImport)           && $pImport == 0;
144 $pLogs             = DEFAULT_LOGS_PURGEDAYS               if defined($pLogs)             && $pLogs == 0;
145 $zebraqueue_days   = DEFAULT_ZEBRAQ_PURGEDAYS             if defined($zebraqueue_days)   && $zebraqueue_days == 0;
146 $mail              = DEFAULT_MAIL_PURGEDAYS               if defined($mail)              && $mail == 0;
147 $pSearchhistory    = DEFAULT_SEARCHHISTORY_PURGEDAYS      if defined($pSearchhistory)    && $pSearchhistory == 0;
148 $pListShareInvites = DEFAULT_SHARE_INVITATION_EXPIRY_DAYS if defined($pListShareInvites) && $pListShareInvites == 0;
149 $pDebarments       = DEFAULT_DEBARMENTS_PURGEDAYS         if defined($pDebarments)       && $pDebarments == 0;
150
151 if ($help) {
152     usage(0);
153 }
154
155 unless ( $sessions
156     || $zebraqueue_days
157     || $mail
158     || $purge_merged
159     || $pImport
160     || $pLogs
161     || $fees_days
162     || $pSearchhistory
163     || $pZ3950
164     || $pListShareInvites
165     || $pDebarments
166     || $allDebarments
167     || $pExpSelfReg
168     || $pUnvSelfReg
169     || $special_holidays_days
170     || $temp_uploads
171     || defined $uploads_missing
172     || $oauth_tokens
173     || $pStatistics
174 ) {
175     print "You did not specify any cleanup work for the script to do.\n\n";
176     usage(1);
177 }
178
179 if ($pDebarments && $allDebarments) {
180     print "You can not specify both --restrictions and --all-restrictions.\n\n";
181     usage(1);
182 }
183
184 cronlogaction();
185
186 my $dbh = C4::Context->dbh();
187 my $sth;
188 my $sth2;
189 my $count;
190
191 if ( $sessions && !$sess_days ) {
192     if ($verbose) {
193         print "Session purge triggered.\n";
194         $sth = $dbh->prepare(q{ SELECT COUNT(*) FROM sessions });
195         $sth->execute() or die $dbh->errstr;
196         my @count_arr = $sth->fetchrow_array;
197         print "$count_arr[0] entries will be deleted.\n";
198     }
199     $sth = $dbh->prepare(q{ TRUNCATE sessions });
200     $sth->execute() or die $dbh->errstr;
201     if ($verbose) {
202         print "Done with session purge.\n";
203     }
204 }
205 elsif ( $sessions && $sess_days > 0 ) {
206     print "Session purge triggered with days>$sess_days.\n" if $verbose;
207     RemoveOldSessions();
208     print "Done with session purge with days>$sess_days.\n" if $verbose;
209 }
210
211 if ($zebraqueue_days) {
212     $count = 0;
213     print "Zebraqueue purge triggered for $zebraqueue_days days.\n" if $verbose;
214     $sth = $dbh->prepare(
215         q{
216             SELECT id,biblio_auth_number,server,time
217             FROM zebraqueue
218             WHERE done=1 AND time < date_sub(curdate(), INTERVAL ? DAY)
219         }
220     );
221     $sth->execute($zebraqueue_days) or die $dbh->errstr;
222     $sth2 = $dbh->prepare(q{ DELETE FROM zebraqueue WHERE id=? });
223     while ( my $record = $sth->fetchrow_hashref ) {
224         $sth2->execute( $record->{id} ) or die $dbh->errstr;
225         $count++;
226     }
227     print "$count records were deleted.\nDone with zebraqueue purge.\n" if $verbose;
228 }
229
230 if ($mail) {
231     print "Mail queue purge triggered for $mail days.\n" if $verbose;
232     $sth = $dbh->prepare(
233         q{
234             DELETE FROM message_queue
235             WHERE time_queued < date_sub(curdate(), INTERVAL ? DAY)
236         }
237     );
238     $sth->execute($mail) or die $dbh->errstr;
239     $count = $sth->rows;
240     $sth->finish;
241     print "$count messages were deleted from the mail queue.\nDone with message_queue purge.\n" if $verbose;
242 }
243
244 if ($purge_merged) {
245     print "Purging completed entries from need_merge_authorities.\n" if $verbose;
246     $sth = $dbh->prepare(q{ DELETE FROM need_merge_authorities WHERE done=1 });
247     $sth->execute() or die $dbh->errstr;
248     print "Done with purging need_merge_authorities.\n" if $verbose;
249 }
250
251 if ($pImport) {
252     print "Purging records from import tables.\n" if $verbose;
253     PurgeImportTables();
254     print "Done with purging import tables.\n" if $verbose;
255 }
256
257 if ($pZ3950) {
258     print "Purging Z39.50 records from import tables.\n" if $verbose;
259     PurgeZ3950();
260     print "Done with purging Z39.50 records from import tables.\n" if $verbose;
261 }
262
263 if ($pLogs) {
264     print "Purging records from action_logs.\n" if $verbose;
265     $sth = $dbh->prepare(
266         q{
267             DELETE FROM action_logs
268             WHERE timestamp < date_sub(curdate(), INTERVAL ? DAY)
269         }
270     );
271     $sth->execute($pLogs) or die $dbh->errstr;
272     print "Done with purging action_logs.\n" if $verbose;
273 }
274
275 if ($fees_days) {
276     print "Purging records from accountlines.\n" if $verbose;
277     purge_zero_balance_fees( $fees_days );
278     print "Done purging records from accountlines.\n" if $verbose;
279 }
280
281 if ($pSearchhistory) {
282     print "Purging records older than $pSearchhistory from search_history.\n" if $verbose;
283     C4::Search::History::delete({ interval => $pSearchhistory });
284     print "Done with purging search_history.\n" if $verbose;
285 }
286
287 if ($pListShareInvites) {
288     print "Purging unaccepted list share invites older than $pListShareInvites days.\n" if $verbose;
289     $sth = $dbh->prepare(
290         q{
291             DELETE FROM virtualshelfshares
292             WHERE invitekey IS NOT NULL
293             AND (sharedate + INTERVAL ? DAY) < NOW()
294         }
295     );
296     $sth->execute($pListShareInvites);
297     print "Done with purging unaccepted list share invites.\n" if $verbose;
298 }
299
300 if ($pDebarments) {
301     print "Expired patrons restrictions purge triggered for $pDebarments days.\n" if $verbose;
302     $count = PurgeDebarments($pDebarments);
303     print "$count restrictions were deleted.\nDone with restrictions purge.\n" if $verbose;
304 }
305
306 if($allDebarments) {
307     print "All expired patrons restrictions purge triggered.\n" if $verbose;
308     $count = PurgeDebarments(0);
309     print "$count restrictions were deleted.\nDone with all restrictions purge.\n" if $verbose;
310 }
311
312 # Handle unsubscribe requests from GDPR consent form, depends on UnsubscribeReflectionDelay preference
313 Koha::Patrons->search_unsubscribed->lock({ expire => 1, remove => 1, verbose => $verbose });
314 # Anonymize patron data, depending on PatronAnonymizeDelay
315 Koha::Patrons->search_anonymize_candidates({ locked => 1 })->anonymize({ verbose => $verbose });
316 # Remove patron data, depending on PatronRemovalDelay (will raise an exception if problem encountered
317 eval { Koha::Patrons->search_anonymized->delete({ move => 1, verbose => $verbose }) };
318 warn $@ if $@;
319
320 if( $pExpSelfReg ) {
321     DeleteExpiredSelfRegs();
322 }
323 if( $pUnvSelfReg ) {
324     DeleteUnverifiedSelfRegs( $pUnvSelfReg );
325 }
326
327 if ($special_holidays_days) {
328     DeleteSpecialHolidays( abs($special_holidays_days) );
329 }
330
331 if( $temp_uploads ) {
332     # Delete temporary uploads, governed by a pref (unless you override)
333     print "Purging temporary uploads.\n" if $verbose;
334     Koha::UploadedFiles->delete_temporary({
335         defined($temp_uploads_days)
336             ? ( override_pref => $temp_uploads_days )
337             : ()
338     });
339     print "Done purging temporary uploads.\n" if $verbose;
340 }
341
342 if( defined $uploads_missing ) {
343     print "Looking for missing uploads\n" if $verbose;
344     my $keep = $uploads_missing == 1 ? 0 : 1;
345     my $count = Koha::UploadedFiles->delete_missing({ keep_record => $keep });
346     if( $keep ) {
347         print "Counted $count missing uploaded files\n";
348     } else {
349         print "Removed $count records for missing uploads\n";
350     }
351 }
352
353 if ($oauth_tokens) {
354     require Koha::OAuthAccessTokens;
355
356     my $count = int Koha::OAuthAccessTokens->search({ expires => { '<=', time } })->delete;
357     say "Removed $count expired OAuth2 tokens" if $verbose;
358 }
359
360 if ($pStatistics) {
361     print "Purging statistics older than $pStatistics days.\n" if $verbose;
362     $sth = $dbh->prepare(
363         q{
364             DELETE FROM statistics
365             WHERE datetime < DATE_SUB(CURDATE(), INTERVAL ? DAY)
366         }
367     );
368     $sth->execute($pStatistics);
369     print "Done with purging statistics.\n" if $verbose;
370 }
371
372 exit(0);
373
374 sub RemoveOldSessions {
375     my ( $id, $a_session, $limit, $lasttime );
376     $limit = time() - 24 * 3600 * $sess_days;
377
378     $sth = $dbh->prepare(q{ SELECT id, a_session FROM sessions });
379     $sth->execute or die $dbh->errstr;
380     $sth->bind_columns( \$id, \$a_session );
381     $sth2  = $dbh->prepare(q{ DELETE FROM sessions WHERE id=? });
382     $count = 0;
383
384     while ( $sth->fetch ) {
385         $lasttime = 0;
386         if ( $a_session =~ /lasttime:\s+'?(\d+)/ ) {
387             $lasttime = $1;
388         }
389         elsif ( $a_session =~ /(ATIME|CTIME):\s+'?(\d+)/ ) {
390             $lasttime = $2;
391         }
392         if ( $lasttime && $lasttime < $limit ) {
393             $sth2->execute($id) or die $dbh->errstr;
394             $count++;
395         }
396     }
397     if ($verbose) {
398         print "$count sessions were deleted.\n";
399     }
400 }
401
402 sub PurgeImportTables {
403
404     #First purge import_records
405     #Delete cascades to import_biblios, import_items and import_record_matches
406     $sth = $dbh->prepare(
407         q{
408             DELETE FROM import_records
409             WHERE upload_timestamp < date_sub(curdate(), INTERVAL ? DAY)
410         }
411     );
412     $sth->execute($pImport) or die $dbh->errstr;
413
414     # Now purge import_batches
415     # Timestamp cannot be used here without care, because records are added
416     # continuously to batches without updating timestamp (Z39.50 search).
417     # So we only delete older empty batches.
418     # This delete will therefore not have a cascading effect.
419     $sth = $dbh->prepare(
420         q{
421             DELETE ba
422             FROM import_batches ba
423             LEFT JOIN import_records re ON re.import_batch_id=ba.import_batch_id
424             WHERE re.import_record_id IS NULL AND
425             ba.upload_timestamp < date_sub(curdate(), INTERVAL ? DAY)
426         }
427     );
428     $sth->execute($pImport) or die $dbh->errstr;
429 }
430
431 sub PurgeZ3950 {
432     $sth = $dbh->prepare(
433         q{
434             DELETE FROM import_batches
435             WHERE batch_type = 'z3950'
436         }
437     );
438     $sth->execute() or die $dbh->errstr;
439 }
440
441 sub PurgeDebarments {
442     require Koha::Patron::Debarments;
443     my $days = shift;
444     $count = 0;
445     $sth   = $dbh->prepare(
446         q{
447             SELECT borrower_debarment_id
448             FROM borrower_debarments
449             WHERE expiration < date_sub(curdate(), INTERVAL ? DAY)
450         }
451     );
452     $sth->execute($days) or die $dbh->errstr;
453     while ( my ($borrower_debarment_id) = $sth->fetchrow_array ) {
454         Koha::Patron::Debarments::DelDebarment($borrower_debarment_id);
455         $count++;
456     }
457     return $count;
458 }
459
460 sub DeleteExpiredSelfRegs {
461     my $cnt= C4::Members::DeleteExpiredOpacRegistrations();
462     print "Removed $cnt expired self-registered borrowers\n" if $verbose;
463 }
464
465 sub DeleteUnverifiedSelfRegs {
466     my $cnt= C4::Members::DeleteUnverifiedOpacRegistrations( $_[0] );
467     print "Removed $cnt unverified self-registrations\n" if $verbose;
468 }
469
470 sub DeleteSpecialHolidays {
471     my ( $days ) = @_;
472
473     my $sth = $dbh->prepare(q{
474         DELETE FROM special_holidays
475         WHERE DATE( CONCAT( year, '-', month, '-', day ) ) < DATE_SUB( CAST(NOW() AS DATE), INTERVAL ? DAY );
476     });
477     my $count = $sth->execute( $days ) + 0;
478     print "Removed $count unique holidays\n" if $verbose;
479 }