Bug 16699: Move Swagger-related files to api/v1/swagger
[koha.git] / misc / cronjobs / cleanup_database.pl
blob8ce0469275665edf37846e8f79e079269fa6ec7e
1 #!/usr/bin/perl
3 # Copyright 2009 PTFS, Inc.
5 # This file is part of Koha.
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.
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.
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>.
20 use Modern::Perl;
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;
30 BEGIN {
31 # find Koha's Perl modules
32 # test carefully before changing this
33 use FindBin;
34 eval { require "$FindBin::Bin/../kohalib.pl" };
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;
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]
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 --unique-holidays DAYS Delete all unique holidays older than DAYS
83 USAGE
84 exit $_[0];
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 my $special_holidays_days;
106 GetOptions(
107 'h|help' => \$help,
108 'sessions' => \$sessions,
109 'sessdays:i' => \$sess_days,
110 'v|verbose' => \$verbose,
111 'm|mail:i' => \$mail,
112 'zebraqueue:i' => \$zebraqueue_days,
113 'merged' => \$purge_merged,
114 'import:i' => \$pImport,
115 'z3950' => \$pZ3950,
116 'logs:i' => \$pLogs,
117 'fees:i' => \$fees_days,
118 'searchhistory:i' => \$pSearchhistory,
119 'list-invites:i' => \$pListShareInvites,
120 'restrictions:i' => \$pDebarments,
121 'all-restrictions' => \$allDebarments,
122 'del-exp-selfreg' => \$pExpSelfReg,
123 'del-unv-selfreg' => \$pUnvSelfReg,
124 'unique-holidays:i' => \$special_holidays_days,
125 ) || usage(1);
127 # Use default values
128 $sessions = 1 if $sess_days && $sess_days > 0;
129 $pImport = DEFAULT_IMPORT_PURGEDAYS if defined($pImport) && $pImport == 0;
130 $pLogs = DEFAULT_LOGS_PURGEDAYS if defined($pLogs) && $pLogs == 0;
131 $zebraqueue_days = DEFAULT_ZEBRAQ_PURGEDAYS if defined($zebraqueue_days) && $zebraqueue_days == 0;
132 $mail = DEFAULT_MAIL_PURGEDAYS if defined($mail) && $mail == 0;
133 $pSearchhistory = DEFAULT_SEARCHHISTORY_PURGEDAYS if defined($pSearchhistory) && $pSearchhistory == 0;
134 $pListShareInvites = DEFAULT_SHARE_INVITATION_EXPIRY_DAYS if defined($pListShareInvites) && $pListShareInvites == 0;
135 $pDebarments = DEFAULT_DEBARMENTS_PURGEDAYS if defined($pDebarments) && $pDebarments == 0;
137 if ($help) {
138 usage(0);
141 unless ( $sessions
142 || $zebraqueue_days
143 || $mail
144 || $purge_merged
145 || $pImport
146 || $pLogs
147 || $fees_days
148 || $pSearchhistory
149 || $pZ3950
150 || $pListShareInvites
151 || $pDebarments
152 || $allDebarments
153 || $pExpSelfReg
154 || $pUnvSelfReg
155 || $special_holidays_days
157 print "You did not specify any cleanup work for the script to do.\n\n";
158 usage(1);
161 if ($pDebarments && $allDebarments) {
162 print "You can not specify both --restrictions and --all-restrictions.\n\n";
163 usage(1);
166 cronlogaction();
168 my $dbh = C4::Context->dbh();
169 my $sth;
170 my $sth2;
171 my $count;
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";
181 $sth = $dbh->prepare(q{ TRUNCATE sessions });
182 $sth->execute() or die $dbh->errstr;
183 if ($verbose) {
184 print "Done with session purge.\n";
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;
193 if ($zebraqueue_days) {
194 $count = 0;
195 print "Zebraqueue purge triggered for $zebraqueue_days days.\n" if $verbose;
196 $sth = $dbh->prepare(
198 SELECT id,biblio_auth_number,server,time
199 FROM zebraqueue
200 WHERE done=1 AND time < date_sub(curdate(), INTERVAL ? DAY)
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++;
209 print "$count records were deleted.\nDone with zebraqueue purge.\n" if $verbose;
212 if ($mail) {
213 print "Mail queue purge triggered for $mail days.\n" if $verbose;
214 $sth = $dbh->prepare(
216 DELETE FROM message_queue
217 WHERE time_queued < date_sub(curdate(), INTERVAL ? DAY)
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;
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;
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;
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;
245 if ($pLogs) {
246 print "Purging records from action_logs.\n" if $verbose;
247 $sth = $dbh->prepare(
249 DELETE FROM action_logs
250 WHERE timestamp < date_sub(curdate(), INTERVAL ? DAY)
253 $sth->execute($pLogs) or die $dbh->errstr;
254 print "Done with purging action_logs.\n" if $verbose;
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;
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;
269 if ($pListShareInvites) {
270 print "Purging unaccepted list share invites older than $pListShareInvites days.\n" if $verbose;
271 $sth = $dbh->prepare(
273 DELETE FROM virtualshelfshares
274 WHERE invitekey IS NOT NULL
275 AND (sharedate + INTERVAL ? DAY) < NOW()
278 $sth->execute($pListShareInvites);
279 print "Done with purging unaccepted list share invites.\n" if $verbose;
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;
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;
294 if( $pExpSelfReg ) {
295 DeleteExpiredSelfRegs();
297 if( $pUnvSelfReg ) {
298 DeleteUnverifiedSelfRegs( $pUnvSelfReg );
301 if ($special_holidays_days) {
302 DeleteSpecialHolidays( abs($special_holidays_days) );
305 exit(0);
307 sub RemoveOldSessions {
308 my ( $id, $a_session, $limit, $lasttime );
309 $limit = time() - 24 * 3600 * $sess_days;
311 $sth = $dbh->prepare(q{ SELECT id, a_session FROM sessions });
312 $sth->execute or die $dbh->errstr;
313 $sth->bind_columns( \$id, \$a_session );
314 $sth2 = $dbh->prepare(q{ DELETE FROM sessions WHERE id=? });
315 $count = 0;
317 while ( $sth->fetch ) {
318 $lasttime = 0;
319 if ( $a_session =~ /lasttime:\s+'?(\d+)/ ) {
320 $lasttime = $1;
322 elsif ( $a_session =~ /(ATIME|CTIME):\s+'?(\d+)/ ) {
323 $lasttime = $2;
325 if ( $lasttime && $lasttime < $limit ) {
326 $sth2->execute($id) or die $dbh->errstr;
327 $count++;
330 if ($verbose) {
331 print "$count sessions were deleted.\n";
335 sub PurgeImportTables {
337 #First purge import_records
338 #Delete cascades to import_biblios, import_items and import_record_matches
339 $sth = $dbh->prepare(
341 DELETE FROM import_records
342 WHERE upload_timestamp < date_sub(curdate(), INTERVAL ? DAY)
345 $sth->execute($pImport) or die $dbh->errstr;
347 # Now purge import_batches
348 # Timestamp cannot be used here without care, because records are added
349 # continuously to batches without updating timestamp (Z39.50 search).
350 # So we only delete older empty batches.
351 # This delete will therefore not have a cascading effect.
352 $sth = $dbh->prepare(
354 DELETE ba
355 FROM import_batches ba
356 LEFT JOIN import_records re ON re.import_batch_id=ba.import_batch_id
357 WHERE re.import_record_id IS NULL AND
358 ba.upload_timestamp < date_sub(curdate(), INTERVAL ? DAY)
361 $sth->execute($pImport) or die $dbh->errstr;
364 sub PurgeZ3950 {
365 $sth = $dbh->prepare(
367 DELETE FROM import_batches
368 WHERE batch_type = 'z3950'
371 $sth->execute() or die $dbh->errstr;
374 sub PurgeDebarments {
375 require Koha::Patron::Debarments;
376 my $days = shift;
377 $count = 0;
378 $sth = $dbh->prepare(
380 SELECT borrower_debarment_id
381 FROM borrower_debarments
382 WHERE expiration < date_sub(curdate(), INTERVAL ? DAY)
385 $sth->execute($days) or die $dbh->errstr;
386 while ( my ($borrower_debarment_id) = $sth->fetchrow_array ) {
387 Koha::Patron::Debarments::DelDebarment($borrower_debarment_id);
388 $count++;
390 return $count;
393 sub DeleteExpiredSelfRegs {
394 my $cnt= C4::Members::DeleteExpiredOpacRegistrations();
395 print "Removed $cnt expired self-registered borrowers\n" if $verbose;
398 sub DeleteUnverifiedSelfRegs {
399 my $cnt= C4::Members::DeleteUnverifiedOpacRegistrations( $_[0] );
400 print "Removed $cnt unverified self-registrations\n" if $verbose;
403 sub DeleteSpecialHolidays {
404 my ( $days ) = @_;
406 my $sth = $dbh->prepare(q{
407 DELETE FROM special_holidays
408 WHERE DATE( CONCAT( year, '-', month, '-', day ) ) < DATE_SUB( CAST(NOW() AS DATE), INTERVAL ? DAY );
410 my $count = $sth->execute( $days ) + 0;
411 print "Removed $count unique holidays\n" if $verbose;