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