MediaWiki 1.43.1
purgeChangedFiles.php
Go to the documentation of this file.
1<?php
25
26// @codeCoverageIgnoreStart
27require_once __DIR__ . '/Maintenance.php';
28// @codeCoverageIgnoreEnd
29
36class PurgeChangedFiles extends Maintenance {
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
59 private $startTimestamp;
60
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
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
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
194 $params = unserialize( $row->log_params );
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
255 protected function verbose( $msg ) {
256 if ( $this->hasOption( 'verbose' ) ) {
257 $this->output( $msg );
258 }
259 }
260}
261
262// @codeCoverageIgnoreStart
263$maintClass = PurgeChangedFiles::class;
264require_once RUN_MAINTENANCE_IF_MAIN;
265// @codeCoverageIgnoreEnd
const NS_FILE
Definition Defines.php:71
array $params
The job parameters.
fileExists( $file)
Checks existence of a file.
getFileSha1( $virtualUrl)
Get the sha1 (base 36) of a file with a given virtual URL/storage path.
getDeletedHashPath( $key)
Get a relative path for a deletion archive key, e.g.
getBackend()
Get the file backend instance.
Definition FileRepo.php:259
getPath()
Return the storage path to the file.
Definition File.php:475
getName()
Return the name of this file.
Definition File.php:347
getTitle()
Return the associated title object.
Definition File.php:377
Local file in the wiki's own database.
Definition LocalFile.php:75
exists()
canRender inherited
purgeOldThumbnails( $archiveName)
Delete cached transformed files for an archived version only.
Local repository that stores files in the local filesystem and registers them in the wiki's own datab...
Definition LocalRepo.php:49
getReplicaDB()
Get a connection to the replica DB.
newFromArchiveName( $title, $archiveName)
Represents a title within MediaWiki.
Definition Title.php:78
Maintenance script that scans the deletion log and purges affected files within a timeframe.
purgeFromLogType( $type)
Purge cache and thumbnails for changes of the given type.
getDeletedPath(LocalRepo $repo, LocalFile $file)
purgeFromArchiveTable(LocalRepo $repo, LocalFile $file)
verbose( $msg)
Send an output message iff the 'verbose' option has been provided.
$wgHTCPRouting
Config variable stub for the HTCPRouting setting, for use by phpdoc and IDEs.