Bug 8258: Use patron's library's notice for DUEDGST and PREDUEDGST
[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 under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along
17 # with Koha; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19
20 use strict;
21 use warnings;
22
23 use constant DEFAULT_ZEBRAQ_PURGEDAYS => 30;
24 use constant DEFAULT_MAIL_PURGEDAYS => 30;
25 use constant DEFAULT_IMPORT_PURGEDAYS => 60;
26 use constant DEFAULT_LOGS_PURGEDAYS => 180;
27 use constant DEFAULT_SEARCHHISTORY_PURGEDAYS => 30;
28
29 BEGIN {
30     # find Koha's Perl modules
31     # test carefully before changing this
32     use FindBin;
33     eval { require "$FindBin::Bin/../kohalib.pl" };
34 }
35
36 use C4::Context;
37 use C4::Dates;
38
39 use C4::Search;
40
41 use Getopt::Long;
42
43 sub usage {
44     print STDERR <<USAGE;
45 Usage: $0 [-h|--help] [--sessions] [--sessdays DAYS] [-v|--verbose] [--zebraqueue DAYS] [-m|--mail] [--merged] [--import DAYS] [--logs DAYS] [--searchhistory DAYS]
46
47    -h --help          prints this help message, and exits, ignoring all
48                       other options
49    --sessions         purge the sessions table.  If you use this while users 
50                       are logged into Koha, they will have to reconnect.
51    --sessdays DAYS    purge only sessions older than DAYS days.
52    -v --verbose       will cause the script to give you a bit more information
53                       about the run.
54    --zebraqueue DAYS  purge completed zebraqueue entries older than DAYS days.
55                       Defaults to 30 days if no days specified.
56    -m --mail DAYS     purge items from the mail queue that are older than DAYS days.
57                       Defaults to 30 days if no days specified.
58    --merged           purged completed entries from need_merge_authorities.
59    --import DAYS      purge records from import tables older than DAYS days.
60                       Defaults to 60 days if no days specified.
61    --z3950            purge records from import tables that are the result
62                       of Z39.50 searches
63    --logs DAYS        purge entries from action_logs older than DAYS days.
64                       Defaults to 180 days if no days specified.
65    --searchhistory DAYS  purge entries from search_history older than DAYS days.
66                          Defaults to 30 days if no days specified
67 USAGE
68     exit $_[0];
69 }
70
71 my (
72     $help,            $sessions,       $sess_days,    $verbose,
73     $zebraqueue_days, $mail,           $purge_merged, $pImport,
74     $pLogs,           $pSearchhistory, $pZ3950
75 );
76
77 GetOptions(
78     'h|help'       => \$help,
79     'sessions'     => \$sessions,
80     'sessdays:i'   => \$sess_days,
81     'v|verbose'    => \$verbose,
82     'm|mail:i'       => \$mail,
83     'zebraqueue:i' => \$zebraqueue_days,
84     'merged'       => \$purge_merged,
85     'import:i'     => \$pImport,
86     'z3950'        => \$pZ3950,
87     'logs:i'       => \$pLogs,
88     'searchhistory:i' => \$pSearchhistory,
89 ) || usage(1);
90
91 $sessions=1 if $sess_days && $sess_days>0;
92 # if --import, --logs, --zebraqueue or --searchhistory were passed without number of days,
93 # use defaults
94 $pImport= DEFAULT_IMPORT_PURGEDAYS if defined($pImport) && $pImport==0;
95 $pLogs= DEFAULT_LOGS_PURGEDAYS if defined($pLogs) && $pLogs==0;
96 $zebraqueue_days= DEFAULT_ZEBRAQ_PURGEDAYS if defined($zebraqueue_days) && $zebraqueue_days==0;
97 $mail= DEFAULT_MAIL_PURGEDAYS if defined($mail) && $mail==0;
98 $pSearchhistory= DEFAULT_SEARCHHISTORY_PURGEDAYS if defined($pSearchhistory) && $pSearchhistory==0;
99
100 if ($help) {
101     usage(0);
102 }
103
104 unless ( $sessions
105     || $zebraqueue_days
106     || $mail
107     || $purge_merged
108     || $pImport
109     || $pLogs
110     || $pSearchhistory
111     || $pZ3950 )
112 {
113     print "You did not specify any cleanup work for the script to do.\n\n";
114     usage(1);
115 }
116
117 my $dbh = C4::Context->dbh();
118 my $query;
119 my $sth;
120 my $sth2;
121 my $count;
122
123 if ( $sessions && !$sess_days ) {
124     if ($verbose) {
125         print "Session purge triggered.\n";
126         $sth = $dbh->prepare("SELECT COUNT(*) FROM sessions");
127         $sth->execute() or die $dbh->errstr;
128         my @count_arr = $sth->fetchrow_array;
129         print "$count_arr[0] entries will be deleted.\n";
130     }
131     $sth = $dbh->prepare("TRUNCATE sessions");
132     $sth->execute() or die $dbh->errstr;
133     if ($verbose) {
134         print "Done with session purge.\n";
135     }
136 } elsif ( $sessions && $sess_days > 0 ) {
137     if ($verbose) {
138         print "Session purge triggered with days>$sess_days.\n";
139     }
140     RemoveOldSessions();
141     if ($verbose) {
142         print "Done with session purge with days>$sess_days.\n";
143     }
144 }
145
146 if ($zebraqueue_days) {
147     $count = 0;
148     if ($verbose) {
149         print "Zebraqueue purge triggered for $zebraqueue_days days.\n";
150     }
151     $sth = $dbh->prepare(
152         "SELECT id,biblio_auth_number,server,time FROM zebraqueue
153                           WHERE done=1 and time < date_sub(curdate(), interval ? day)"
154     );
155     $sth->execute($zebraqueue_days) or die $dbh->errstr;
156     $sth2 = $dbh->prepare("DELETE FROM zebraqueue WHERE id=?");
157     while ( my $record = $sth->fetchrow_hashref ) {
158         $sth2->execute( $record->{id} ) or die $dbh->errstr;
159         $count++;
160     }
161     if ($verbose) {
162         print "$count records were deleted.\nDone with zebraqueue purge.\n";
163     }
164 }
165
166 if ($mail) {
167     print "Mail queue purge triggered for $mail days.\n" if ($verbose);
168
169     $sth = $dbh->prepare("DELETE FROM message_queue WHERE time_queued < date_sub(curdate(), interval ? day)");
170     $sth->execute($mail) or die $dbh->errstr;
171     my $count = $sth->rows;
172     $sth->finish;
173
174     print "$count messages were deleted from the mail queue.\nDone with message_queue purge.\n" if ($verbose);
175 }
176
177 if($purge_merged) {
178     print "Purging completed entries from need_merge_authorities.\n" if $verbose;
179     $sth = $dbh->prepare("DELETE FROM need_merge_authorities WHERE done=1");
180     $sth->execute() or die $dbh->errstr;
181     print "Done with purging need_merge_authorities.\n" if $verbose;
182 }
183
184 if($pImport) {
185     print "Purging records from import tables.\n" if $verbose;
186     PurgeImportTables();
187     print "Done with purging import tables.\n" if $verbose;
188 }
189
190 if($pZ3950) {
191     print "Purging Z39.50 records from import tables.\n" if $verbose;
192     PurgeZ3950();
193     print "Done with purging Z39.50 records from import tables.\n" if $verbose;
194 }
195
196 if($pLogs) {
197     print "Purging records from action_logs.\n" if $verbose;
198     $sth = $dbh->prepare("DELETE FROM action_logs WHERE timestamp < date_sub(curdate(), interval ? DAY)");
199     $sth->execute($pLogs) or die $dbh->errstr;
200     print "Done with purging action_logs.\n" if $verbose;
201 }
202
203 if($pSearchhistory) {
204     print "Purging records older than $pSearchhistory from search_history.\n" if $verbose;
205     PurgeSearchHistory($pSearchhistory);
206     print "Done with purging search_history.\n" if $verbose;
207 }
208
209 exit(0);
210
211 sub RemoveOldSessions {
212     my ( $id, $a_session, $limit, $lasttime );
213     $limit = time() - 24 * 3600 * $sess_days;
214
215     $sth = $dbh->prepare("SELECT id, a_session FROM sessions");
216     $sth->execute or die $dbh->errstr;
217     $sth->bind_columns( \$id, \$a_session );
218     $sth2  = $dbh->prepare("DELETE FROM sessions WHERE id=?");
219     $count = 0;
220
221     while ( $sth->fetch ) {
222         $lasttime = 0;
223         if ( $a_session =~ /lasttime:\s+'?(\d+)/ ) {
224             $lasttime = $1;
225         } elsif ( $a_session =~ /(ATIME|CTIME):\s+'?(\d+)/ ) {
226             $lasttime = $2;
227         }
228         if ( $lasttime && $lasttime < $limit ) {
229             $sth2->execute($id) or die $dbh->errstr;
230             $count++;
231         }
232     }
233     if ($verbose) {
234         print "$count sessions were deleted.\n";
235     }
236 }
237
238 sub PurgeImportTables {
239     #First purge import_records
240     #Delete cascades to import_biblios, import_items and import_record_matches
241     $sth = $dbh->prepare("DELETE FROM import_records WHERE upload_timestamp < date_sub(curdate(), interval ? DAY)");
242     $sth->execute($pImport) or die $dbh->errstr;
243
244     # Now purge import_batches
245     # Timestamp cannot be used here without care, because records are added
246     # continuously to batches without updating timestamp (Z39.50 search).
247     # So we only delete older empty batches.
248     # This delete will therefore not have a cascading effect.
249     $sth = $dbh->prepare("DELETE ba
250  FROM import_batches ba
251  LEFT JOIN import_records re ON re.import_batch_id=ba.import_batch_id
252  WHERE re.import_record_id IS NULL AND
253  ba.upload_timestamp < date_sub(curdate(), interval ? DAY)");
254     $sth->execute($pImport) or die $dbh->errstr;
255 }
256
257
258 sub PurgeZ3950 {
259     $sth = $dbh->prepare(q{
260         DELETE FROM import_batches WHERE batch_type = 'z3950'
261     });
262     $sth->execute() or die $dbh->errstr;
263 }