Debian Codegraph @

maintenance/purgeChangedFiles.php

raw symbols SCIP
1 <?php
2 /**
3 * Scan the logging table and purge affected files within a timeframe.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Maintenance
22 */
23
24 use MediaWiki\Title\Title;
25
26 // @codeCoverageIgnoreStart
27 require_once __DIR__ . '/Maintenance.php';
28 // @codeCoverageIgnoreEnd
29
30 /**
31 * Maintenance script that scans the deletion log and purges affected files
32 * within a timeframe.
33 *
34 * @ingroup Maintenance
35 */
36 class PurgeChangedFiles extends Maintenance {
37 /**
38 * Mapping from type option to log type and actions.
39 * @var array
40 */
41 private static $typeMappings = [
42 'created' => [
43 'upload' => [ 'upload' ],
44 'import' => [ 'upload', 'interwiki' ],
45 ],
46 'deleted' => [
47 'delete' => [ 'delete', 'revision' ],
48 'suppress' => [ 'delete', 'revision' ],
49 ],
50 'modified' => [
51 'upload' => [ 'overwrite', 'revert' ],
52 'move' => [ 'move', 'move_redir' ],
53 ],
54 ];
55
56 /**
57 * @var string
58 */
59 private $startTimestamp;
60
61 /**
62 * @var string
63 */
64 private $endTimestamp;
65
66 public function __construct() {
67 parent::__construct();
68 $this->addDescription( 'Scan the logging table and purge files and thumbnails.' );
69 $this->addOption( 'starttime', 'Starting timestamp', true, true );
70 $this->addOption( 'endtime', 'Ending timestamp', true, true );
71 $this->addOption( 'type', 'Comma-separated list of types of changes to send purges for (' .
72 implode( ',', array_keys( self::$typeMappings ) ) . ',all)', false, true );
73 $this->addOption( 'htcp-dest', 'HTCP announcement destination (IP:port)', false, true );
74 $this->addOption( 'dry-run', 'Do not send purge requests' );
75 $this->addOption( 'sleep-per-batch', 'Milliseconds to sleep between batches', false, true );
76 $this->addOption( 'verbose', 'Show more output', false, false, 'v' );
77 $this->setBatchSize( 100 );
78 }
79
80 public function execute() {
81 global $wgHTCPRouting;
82
83 if ( $this->hasOption( 'htcp-dest' ) ) {
84 $parts = explode( ':', $this->getOption( 'htcp-dest' ), 2 );
85 if ( count( $parts ) < 2 ) {
86 // Add default htcp port
87 $parts[] = '4827';
88 }
89
90 // Route all HTCP messages to provided host:port
91 $wgHTCPRouting = [
92 '' => [ 'host' => $parts[0], 'port' => $parts[1] ],
93 ];
94 $this->verbose( "HTCP broadcasts to {$parts[0]}:{$parts[1]}\n" );
95 }
96
97 // Find out which actions we should be concerned with
98 $typeOpt = $this->getOption( 'type', 'all' );
99 if ( $typeOpt === 'all' ) {
100 // Convert 'all' to all registered types
101 $typeOpt = implode( ',', array_keys( self::$typeMappings ) );
102 }
103 $typeList = explode( ',', $typeOpt );
104 foreach ( $typeList as $type ) {
105 if ( !isset( self::$typeMappings[$type] ) ) {
106 $this->error( "\nERROR: Unknown type: {$type}\n" );
107 $this->maybeHelp( true );
108 }
109 }
110
111 // Validate the timestamps
112 $dbr = $this->getReplicaDB();
113 $this->startTimestamp = $dbr->timestamp( $this->getOption( 'starttime' ) );
114 $this->endTimestamp = $dbr->timestamp( $this->getOption( 'endtime' ) );
115
116 if ( $this->startTimestamp > $this->endTimestamp ) {
117 $this->error( "\nERROR: starttime after endtime\n" );
118 $this->maybeHelp( true );
119 }
120
121 // Turn on verbose when dry-run is enabled
122 if ( $this->hasOption( 'dry-run' ) ) {
123 $this->setOption( 'verbose', 1 );
124 }
125
126 $this->verbose( 'Purging files that were: ' . implode( ', ', $typeList ) . "\n" );
127 foreach ( $typeList as $type ) {
128 $this->verbose( "Checking for {$type} files...\n" );
129 $this->purgeFromLogType( $type );
130 if ( !$this->hasOption( 'dry-run' ) ) {
131 $this->verbose( "...{$type} files purged.\n\n" );
132 }
133 }
134 }
135
136 /**
137 * Purge cache and thumbnails for changes of the given type.
138 *
139 * @param string $type Type of change to find
140 */
141 protected function purgeFromLogType( $type ) {
142 $repo = $this->getServiceContainer()->getRepoGroup()->getLocalRepo();
143 $dbr = $this->getReplicaDB();
144
145 foreach ( self::$typeMappings[$type] as $logType => $logActions ) {
146 $this->verbose( "Scanning for {$logType}/" . implode( ',', $logActions ) . "\n" );
147
148 $res = $dbr->newSelectQueryBuilder()
149 ->select( [ 'log_title', 'log_timestamp', 'log_params' ] )
150 ->from( 'logging' )
151 ->where( [
152 'log_namespace' => NS_FILE,
153 'log_type' => $logType,
154 'log_action' => $logActions,
155 $dbr->expr( 'log_timestamp', '>=', $this->startTimestamp ),
156 $dbr->expr( 'log_timestamp', '<=', $this->endTimestamp ),
157 ] )
158 ->caller( __METHOD__ )->fetchResultSet();
159
160 $bSize = 0;
161 foreach ( $res as $row ) {
162 $file = $repo->newFile( Title::makeTitle( NS_FILE, $row->log_title ) );
163
164 if ( $this->hasOption( 'dry-run' ) ) {
165 $this->verbose( "{$type}[{$row->log_timestamp}]: {$row->log_title}\n" );
166 continue;
167 }
168
169 // Purge current version and its thumbnails
170 $file->purgeCache();
171 // Purge the old versions and their thumbnails
172 foreach ( $file->getHistory() as $oldFile ) {
173 $oldFile->purgeCache();
174 }
175
176 if ( $logType === 'delete' ) {
177 // If there is an orphaned storage file... delete it
178 if ( !$file->exists() && $repo->fileExists( $file->getPath() ) ) {
179 $dpath = $this->getDeletedPath( $repo, $file );
180 if ( $repo->fileExists( $dpath ) ) {
181 // Check to avoid data loss
182 $repo->getBackend()->delete( [ 'src' => $file->getPath() ] );
183 $this->verbose( "Deleted orphan file: {$file->getPath()}.\n" );
184 } else {
185 $this->error( "File was not deleted: {$file->getPath()}.\n" );
186 }
187 }
188
189 // Purge items from fileachive table (rows are likely here)
190 $this->purgeFromArchiveTable( $repo, $file );
191 } elseif ( $logType === 'move' ) {
192 // Purge the target file as well
193 // (only handles hard-coded core logs, so no need to pass log type/action here)
194 $params = LogEntryBase::extractParams( $row->log_params, null );
195 if ( isset( $params['4::target'] ) ) {
196 $target = $params['4::target'];
197 $targetFile = $repo->newFile( Title::makeTitle( NS_FILE, $target ) );
198 $targetFile->purgeCache();
199 $this->verbose( "Purged file {$target}; move target @{$row->log_timestamp}.\n" );
200 }
201 }
202
203 $this->verbose( "Purged file {$row->log_title}; {$type} @{$row->log_timestamp}.\n" );
204
205 if ( $this->hasOption( 'sleep-per-batch' ) && ++$bSize > $this->getBatchSize() ) {
206 $bSize = 0;
207 // sleep-per-batch is milliseconds, usleep wants micro seconds.
208 usleep( 1000 * (int)$this->getOption( 'sleep-per-batch' ) );
209 }
210 }
211 }
212 }
213
214 protected function purgeFromArchiveTable( LocalRepo $repo, LocalFile $file ) {
215 $dbr = $repo->getReplicaDB();
216 $res = $dbr->newSelectQueryBuilder()
217 ->select( [ 'fa_archive_name' ] )
218 ->from( 'filearchive' )
219 ->where( [ 'fa_name' => $file->getName() ] )
220 ->caller( __METHOD__ )->fetchResultSet();
221
222 foreach ( $res as $row ) {
223 if ( $row->fa_archive_name === null ) {
224 // Was not an old version (current version names checked already)
225 continue;
226 }
227 $ofile = $repo->newFromArchiveName( $file->getTitle(), $row->fa_archive_name );
228 // If there is an orphaned storage file still there...delete it
229 if ( !$file->exists() && $repo->fileExists( $ofile->getPath() ) ) {
230 $dpath = $this->getDeletedPath( $repo, $ofile );
231 if ( $repo->fileExists( $dpath ) ) {
232 // Check to avoid data loss
233 $repo->getBackend()->delete( [ 'src' => $ofile->getPath() ] );
234 $this->output( "Deleted orphan file: {$ofile->getPath()}.\n" );
235 } else {
236 $this->error( "File was not deleted: {$ofile->getPath()}.\n" );
237 }
238 }
239 $file->purgeOldThumbnails( $row->fa_archive_name );
240 }
241 }
242
243 protected function getDeletedPath( LocalRepo $repo, LocalFile $file ) {
244 $hash = $repo->getFileSha1( $file->getPath() );
245 $key = "{$hash}.{$file->getExtension()}";
246
247 return $repo->getDeletedHashPath( $key ) . $key;
248 }
249
250 /**
251 * Send an output message iff the 'verbose' option has been provided.
252 *
253 * @param string $msg Message to output
254 */
255 protected function verbose( $msg ) {
256 if ( $this->hasOption( 'verbose' ) ) {
257 $this->output( $msg );
258 }
259 }
260 }
261
262 // @codeCoverageIgnoreStart
263 $maintClass = PurgeChangedFiles::class;
264 require_once RUN_MAINTENANCE_IF_MAIN;
265 // @codeCoverageIgnoreEnd