Bug 9739: (follow-up) cosmetic changes
[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    --logs DAYS        purge entries from action_logs older than DAYS days.
62                       Defaults to 180 days if no days specified.
63    --searchhistory DAYS  purge entries from search_history older than DAYS days.
64                          Defaults to 30 days if no days specified
65 USAGE
66     exit $_[0];
67 }
68
69 my ( $help, $sessions, $sess_days, $verbose, $zebraqueue_days, $mail, $purge_merged, $pImport, $pLogs, $pSearchhistory);
70
71 GetOptions(
72     'h|help'       => \$help,
73     'sessions'     => \$sessions,
74     'sessdays:i'   => \$sess_days,
75     'v|verbose'    => \$verbose,
76     'm|mail:i'       => \$mail,
77     'zebraqueue:i' => \$zebraqueue_days,
78     'merged'       => \$purge_merged,
79     'import:i'     => \$pImport,
80     'logs:i'       => \$pLogs,
81     'searchhistory:i' => \$pSearchhistory,
82 ) || usage(1);
83
84 $sessions=1 if $sess_days && $sess_days>0;
85 # if --import, --logs, --zebraqueue or --searchhistory were passed without number of days,
86 # use defaults
87 $pImport= DEFAULT_IMPORT_PURGEDAYS if defined($pImport) && $pImport==0;
88 $pLogs= DEFAULT_LOGS_PURGEDAYS if defined($pLogs) && $pLogs==0;
89 $zebraqueue_days= DEFAULT_ZEBRAQ_PURGEDAYS if defined($zebraqueue_days) && $zebraqueue_days==0;
90 $mail= DEFAULT_MAIL_PURGEDAYS if defined($mail) && $mail==0;
91 $pSearchhistory= DEFAULT_SEARCHHISTORY_PURGEDAYS if defined($pSearchhistory) && $pSearchhistory==0;
92
93 if ($help) {
94     usage(0);
95 }
96
97 if ( !( $sessions || $zebraqueue_days || $mail || $purge_merged || $pImport || $pLogs || $pSearchhistory ) ) {
98     print "You did not specify any cleanup work for the script to do.\n\n";
99     usage(1);
100 }
101
102 my $dbh = C4::Context->dbh();
103 my $query;
104 my $sth;
105 my $sth2;
106 my $count;
107
108 if ( $sessions && !$sess_days ) {
109     if ($verbose) {
110         print "Session purge triggered.\n";
111         $sth = $dbh->prepare("SELECT COUNT(*) FROM sessions");
112         $sth->execute() or die $dbh->errstr;
113         my @count_arr = $sth->fetchrow_array;
114         print "$count_arr[0] entries will be deleted.\n";
115     }
116     $sth = $dbh->prepare("TRUNCATE sessions");
117     $sth->execute() or die $dbh->errstr;
118     if ($verbose) {
119         print "Done with session purge.\n";
120     }
121 } elsif ( $sessions && $sess_days > 0 ) {
122     if ($verbose) {
123         print "Session purge triggered with days>$sess_days.\n";
124     }
125     RemoveOldSessions();
126     if ($verbose) {
127         print "Done with session purge with days>$sess_days.\n";
128     }
129 }
130
131 if ($zebraqueue_days) {
132     $count = 0;
133     if ($verbose) {
134         print "Zebraqueue purge triggered for $zebraqueue_days days.\n";
135     }
136     $sth = $dbh->prepare(
137         "SELECT id,biblio_auth_number,server,time FROM zebraqueue
138                           WHERE done=1 and time < date_sub(curdate(), interval ? day)"
139     );
140     $sth->execute($zebraqueue_days) or die $dbh->errstr;
141     $sth2 = $dbh->prepare("DELETE FROM zebraqueue WHERE id=?");
142     while ( my $record = $sth->fetchrow_hashref ) {
143         $sth2->execute( $record->{id} ) or die $dbh->errstr;
144         $count++;
145     }
146     if ($verbose) {
147         print "$count records were deleted.\nDone with zebraqueue purge.\n";
148     }
149 }
150
151 if ($mail) {
152     print "Mail queue purge triggered for $mail days.\n" if ($verbose);
153
154     $sth = $dbh->prepare("DELETE FROM message_queue WHERE time_queued < date_sub(curdate(), interval ? day)");
155     $sth->execute($mail) or die $dbh->errstr;
156     my $count = $sth->rows;
157     $sth->finish;
158
159     print "$count messages were deleted from the mail queue.\nDone with message_queue purge.\n" if ($verbose);
160 }
161
162 if($purge_merged) {
163     print "Purging completed entries from need_merge_authorities.\n" if $verbose;
164     $sth = $dbh->prepare("DELETE FROM need_merge_authorities WHERE done=1");
165     $sth->execute() or die $dbh->errstr;
166     print "Done with purging need_merge_authorities.\n" if $verbose;
167 }
168
169 if($pImport) {
170     print "Purging records from import tables.\n" if $verbose;
171     PurgeImportTables();
172     print "Done with purging import tables.\n" if $verbose;
173 }
174
175 if($pLogs) {
176     print "Purging records from action_logs.\n" if $verbose;
177     $sth = $dbh->prepare("DELETE FROM action_logs WHERE timestamp < date_sub(curdate(), interval ? DAY)");
178     $sth->execute($pLogs) or die $dbh->errstr;
179     print "Done with purging action_logs.\n" if $verbose;
180 }
181
182 if($pSearchhistory) {
183     print "Purging records older than $pSearchhistory from search_history.\n" if $verbose;
184     PurgeSearchHistory($pSearchhistory);
185     print "Done with purging search_history.\n" if $verbose;
186 }
187
188 exit(0);
189
190 sub RemoveOldSessions {
191     my ( $id, $a_session, $limit, $lasttime );
192     $limit = time() - 24 * 3600 * $sess_days;
193
194     $sth = $dbh->prepare("SELECT id, a_session FROM sessions");
195     $sth->execute or die $dbh->errstr;
196     $sth->bind_columns( \$id, \$a_session );
197     $sth2  = $dbh->prepare("DELETE FROM sessions WHERE id=?");
198     $count = 0;
199
200     while ( $sth->fetch ) {
201         $lasttime = 0;
202         if ( $a_session =~ /lasttime:\s+'?(\d+)/ ) {
203             $lasttime = $1;
204         } elsif ( $a_session =~ /(ATIME|CTIME):\s+'?(\d+)/ ) {
205             $lasttime = $2;
206         }
207         if ( $lasttime && $lasttime < $limit ) {
208             $sth2->execute($id) or die $dbh->errstr;
209             $count++;
210         }
211     }
212     if ($verbose) {
213         print "$count sessions were deleted.\n";
214     }
215 }
216
217 sub PurgeImportTables {
218     #First purge import_records
219     #Delete cascades to import_biblios, import_items and import_record_matches
220     $sth = $dbh->prepare("DELETE FROM import_records WHERE upload_timestamp < date_sub(curdate(), interval ? DAY)");
221     $sth->execute($pImport) or die $dbh->errstr;
222
223     # Now purge import_batches
224     # Timestamp cannot be used here without care, because records are added
225     # continuously to batches without updating timestamp (z3950 search).
226     # So we only delete older empty batches.
227     # This delete will therefore not have a cascading effect.
228     $sth = $dbh->prepare("DELETE ba
229  FROM import_batches ba
230  LEFT JOIN import_records re ON re.import_batch_id=ba.import_batch_id
231  WHERE re.import_record_id IS NULL AND
232  ba.upload_timestamp < date_sub(curdate(), interval ? DAY)");
233     $sth->execute($pImport) or die $dbh->errstr;
234 }