MediaWiki master
purgeChangedFiles.php
Go to the documentation of this file.
1<?php
14
15// @codeCoverageIgnoreStart
16require_once __DIR__ . '/Maintenance.php';
17// @codeCoverageIgnoreEnd
18
30 private static $typeMappings = [
31 'created' => [
32 'upload' => [ 'upload' ],
33 'import' => [ 'upload', 'interwiki' ],
34 ],
35 'deleted' => [
36 'delete' => [ 'delete', 'revision' ],
37 'suppress' => [ 'delete', 'revision' ],
38 ],
39 'modified' => [
40 'upload' => [ 'overwrite', 'revert' ],
41 'move' => [ 'move', 'move_redir' ],
42 ],
43 ];
44
48 private $startTimestamp;
49
53 private $endTimestamp;
54
55 public function __construct() {
56 parent::__construct();
57 $this->addDescription( 'Scan the logging table and purge files and thumbnails.' );
58 $this->addOption( 'starttime', 'Starting timestamp', true, true );
59 $this->addOption( 'endtime', 'Ending timestamp', true, true );
60 $this->addOption( 'type', 'Comma-separated list of types of changes to send purges for (' .
61 implode( ',', array_keys( self::$typeMappings ) ) . ',all)', false, true );
62 $this->addOption( 'htcp-dest', 'HTCP announcement destination (IP:port)', false, true );
63 $this->addOption( 'dry-run', 'Do not send purge requests' );
64 $this->addOption( 'sleep-per-batch', 'Milliseconds to sleep between batches', false, true );
65 $this->addOption( 'verbose', 'Show more output', false, false, 'v' );
66 $this->setBatchSize( 100 );
67 }
68
69 public function execute() {
70 global $wgHTCPRouting;
71
72 if ( $this->hasOption( 'htcp-dest' ) ) {
73 $parts = explode( ':', $this->getOption( 'htcp-dest' ), 2 );
74 if ( count( $parts ) < 2 ) {
75 // Add default htcp port
76 $parts[] = '4827';
77 }
78
79 // Route all HTCP messages to provided host:port
81 '' => [ 'host' => $parts[0], 'port' => $parts[1] ],
82 ];
83 $this->verbose( "HTCP broadcasts to {$parts[0]}:{$parts[1]}\n" );
84 }
85
86 // Find out which actions we should be concerned with
87 $typeOpt = $this->getOption( 'type', 'all' );
88 if ( $typeOpt === 'all' ) {
89 // Convert 'all' to all registered types
90 $typeOpt = implode( ',', array_keys( self::$typeMappings ) );
91 }
92 $typeList = explode( ',', $typeOpt );
93 foreach ( $typeList as $type ) {
94 if ( !isset( self::$typeMappings[$type] ) ) {
95 $this->error( "\nERROR: Unknown type: {$type}\n" );
96 $this->maybeHelp( true );
97 }
98 }
99
100 // Validate the timestamps
101 $dbr = $this->getReplicaDB();
102 $this->startTimestamp = $dbr->timestamp( $this->getOption( 'starttime' ) );
103 $this->endTimestamp = $dbr->timestamp( $this->getOption( 'endtime' ) );
104
105 if ( $this->startTimestamp > $this->endTimestamp ) {
106 $this->error( "\nERROR: starttime after endtime\n" );
107 $this->maybeHelp( true );
108 }
109
110 // Turn on verbose when dry-run is enabled
111 if ( $this->hasOption( 'dry-run' ) ) {
112 $this->setOption( 'verbose', 1 );
113 }
114
115 $this->verbose( 'Purging files that were: ' . implode( ', ', $typeList ) . "\n" );
116 foreach ( $typeList as $type ) {
117 $this->verbose( "Checking for {$type} files...\n" );
118 $this->purgeFromLogType( $type );
119 if ( !$this->hasOption( 'dry-run' ) ) {
120 $this->verbose( "...{$type} files purged.\n\n" );
121 }
122 }
123 }
124
130 protected function purgeFromLogType( $type ) {
131 $repo = $this->getServiceContainer()->getRepoGroup()->getLocalRepo();
132 $dbr = $this->getReplicaDB();
133
134 foreach ( self::$typeMappings[$type] as $logType => $logActions ) {
135 $this->verbose( "Scanning for {$logType}/" . implode( ',', $logActions ) . "\n" );
136
137 $res = $dbr->newSelectQueryBuilder()
138 ->select( [ 'log_title', 'log_timestamp', 'log_params' ] )
139 ->from( 'logging' )
140 ->where( [
141 'log_namespace' => NS_FILE,
142 'log_type' => $logType,
143 'log_action' => $logActions,
144 $dbr->expr( 'log_timestamp', '>=', $this->startTimestamp ),
145 $dbr->expr( 'log_timestamp', '<=', $this->endTimestamp ),
146 ] )
147 ->caller( __METHOD__ )->fetchResultSet();
148
149 $bSize = 0;
150 foreach ( $res as $row ) {
151 $file = $repo->newFile( Title::makeTitle( NS_FILE, $row->log_title ) );
152
153 if ( $this->hasOption( 'dry-run' ) ) {
154 $this->verbose( "{$type}[{$row->log_timestamp}]: {$row->log_title}\n" );
155 continue;
156 }
157
158 // Purge current version and its thumbnails
159 $file->purgeCache();
160 // Purge the old versions and their thumbnails
161 foreach ( $file->getHistory() as $oldFile ) {
162 $oldFile->purgeCache();
163 }
164
165 if ( $logType === 'delete' ) {
166 // If there is an orphaned storage file... delete it
167 if ( !$file->exists() && $repo->fileExists( $file->getPath() ) ) {
168 $dpath = $this->getDeletedPath( $repo, $file );
169 if ( $repo->fileExists( $dpath ) ) {
170 // Check to avoid data loss
171 $repo->getBackend()->delete( [ 'src' => $file->getPath() ] );
172 $this->verbose( "Deleted orphan file: {$file->getPath()}.\n" );
173 } else {
174 $this->error( "File was not deleted: {$file->getPath()}.\n" );
175 }
176 }
177
178 // Purge items from fileachive table (rows are likely here)
179 $this->purgeFromArchiveTable( $repo, $file );
180 } elseif ( $logType === 'move' ) {
181 // Purge the target file as well
182
183 $params = unserialize( $row->log_params );
184 if ( isset( $params['4::target'] ) ) {
185 $target = $params['4::target'];
186 $targetFile = $repo->newFile( Title::makeTitle( NS_FILE, $target ) );
187 $targetFile->purgeCache();
188 $this->verbose( "Purged file {$target}; move target @{$row->log_timestamp}.\n" );
189 }
190 }
191
192 $this->verbose( "Purged file {$row->log_title}; {$type} @{$row->log_timestamp}.\n" );
193
194 if ( $this->hasOption( 'sleep-per-batch' ) && ++$bSize > $this->getBatchSize() ) {
195 $bSize = 0;
196 // sleep-per-batch is milliseconds, usleep wants micro seconds.
197 usleep( 1000 * (int)$this->getOption( 'sleep-per-batch' ) );
198 }
199 }
200 }
201 }
202
203 protected function purgeFromArchiveTable( LocalRepo $repo, LocalFile $file ) {
204 $dbr = $repo->getReplicaDB();
205 $res = $dbr->newSelectQueryBuilder()
206 ->select( [ 'fa_archive_name' ] )
207 ->from( 'filearchive' )
208 ->where( [ 'fa_name' => $file->getName() ] )
209 ->caller( __METHOD__ )->fetchResultSet();
210
211 foreach ( $res as $row ) {
212 if ( $row->fa_archive_name === null ) {
213 // Was not an old version (current version names checked already)
214 continue;
215 }
216 $ofile = $repo->newFromArchiveName( $file->getTitle(), $row->fa_archive_name );
217 // If there is an orphaned storage file still there...delete it
218 if ( !$file->exists() && $repo->fileExists( $ofile->getPath() ) ) {
219 $dpath = $this->getDeletedPath( $repo, $ofile );
220 if ( $repo->fileExists( $dpath ) ) {
221 // Check to avoid data loss
222 $repo->getBackend()->delete( [ 'src' => $ofile->getPath() ] );
223 $this->output( "Deleted orphan file: {$ofile->getPath()}.\n" );
224 } else {
225 $this->error( "File was not deleted: {$ofile->getPath()}.\n" );
226 }
227 }
228 $file->purgeOldThumbnails( $row->fa_archive_name );
229 }
230 }
231
232 protected function getDeletedPath( LocalRepo $repo, LocalFile $file ): string {
233 $hash = $repo->getFileSha1( $file->getPath() );
234 $key = "{$hash}.{$file->getExtension()}";
235
236 return $repo->getDeletedHashPath( $key ) . $key;
237 }
238
244 protected function verbose( $msg ) {
245 if ( $this->hasOption( 'verbose' ) ) {
246 $this->output( $msg );
247 }
248 }
249}
250
251// @codeCoverageIgnoreStart
252$maintClass = PurgeChangedFiles::class;
253require_once RUN_MAINTENANCE_IF_MAIN;
254// @codeCoverageIgnoreEnd
const NS_FILE
Definition Defines.php:57
getDeletedHashPath( $key)
Get a relative path for a deletion archive key, e.g.
fileExists( $file)
Checks existence of a file.
getBackend()
Get the file backend instance.
Definition FileRepo.php:254
getTitle()
Return the associated title object.
Definition File.php:377
getName()
Return the name of this file.
Definition File.php:347
Local file in the wiki's own database.
Definition LocalFile.php:81
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:45
newFromArchiveName( $title, $archiveName)
getReplicaDB()
Get a connection to the replica DB.
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
getBatchSize()
Returns batch size.
output( $out, $channel=null)
Throw some output to the user.
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
hasOption( $name)
Checks to see if a particular option was set.
setOption(string $name, $value)
Programmatically set the value of the given option.
getOption( $name, $default=null)
Get an option, or return the default.
getReplicaDB(string|false $virtualDomain=false)
error( $err, $die=0)
Throw an error to the user.
getServiceContainer()
Returns the main service container.
maybeHelp( $force=false)
Maybe show the help.
addDescription( $text)
Set the description text.
Represents a title within MediaWiki.
Definition Title.php:69
Maintenance script that scans the deletion log and purges affected files within a timeframe.
execute()
Do the actual work.
__construct()
Default constructor.
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.