MediaWiki  master
purgeChangedFiles.php
Go to the documentation of this file.
1 <?php
25 
26 require_once __DIR__ . '/Maintenance.php';
27 
39  private static $typeMappings = [
40  'created' => [
41  'upload' => [ 'upload' ],
42  'import' => [ 'upload', 'interwiki' ],
43  ],
44  'deleted' => [
45  'delete' => [ 'delete', 'revision' ],
46  'suppress' => [ 'delete', 'revision' ],
47  ],
48  'modified' => [
49  'upload' => [ 'overwrite', 'revert' ],
50  'move' => [ 'move', 'move_redir' ],
51  ],
52  ];
53 
57  private $startTimestamp;
58 
62  private $endTimestamp;
63 
64  public function __construct() {
65  parent::__construct();
66  $this->addDescription( 'Scan the logging table and purge files and thumbnails.' );
67  $this->addOption( 'starttime', 'Starting timestamp', true, true );
68  $this->addOption( 'endtime', 'Ending timestamp', true, true );
69  $this->addOption( 'type', 'Comma-separated list of types of changes to send purges for (' .
70  implode( ',', array_keys( self::$typeMappings ) ) . ',all)', false, true );
71  $this->addOption( 'htcp-dest', 'HTCP announcement destination (IP:port)', false, true );
72  $this->addOption( 'dry-run', 'Do not send purge requests' );
73  $this->addOption( 'sleep-per-batch', 'Milliseconds to sleep between batches', false, true );
74  $this->addOption( 'verbose', 'Show more output', false, false, 'v' );
75  $this->setBatchSize( 100 );
76  }
77 
78  public function execute() {
79  global $wgHTCPRouting;
80 
81  if ( $this->hasOption( 'htcp-dest' ) ) {
82  $parts = explode( ':', $this->getOption( 'htcp-dest' ), 2 );
83  if ( count( $parts ) < 2 ) {
84  // Add default htcp port
85  $parts[] = '4827';
86  }
87 
88  // Route all HTCP messages to provided host:port
89  $wgHTCPRouting = [
90  '' => [ 'host' => $parts[0], 'port' => $parts[1] ],
91  ];
92  $this->verbose( "HTCP broadcasts to {$parts[0]}:{$parts[1]}\n" );
93  }
94 
95  // Find out which actions we should be concerned with
96  $typeOpt = $this->getOption( 'type', 'all' );
97  $validTypes = array_keys( self::$typeMappings );
98  if ( $typeOpt === 'all' ) {
99  // Convert 'all' to all registered types
100  $typeOpt = implode( ',', $validTypes );
101  }
102  $typeList = explode( ',', $typeOpt );
103  foreach ( $typeList as $type ) {
104  if ( !in_array( $type, $validTypes ) ) {
105  $this->error( "\nERROR: Unknown type: {$type}\n" );
106  $this->maybeHelp( true );
107  }
108  }
109 
110  // Validate the timestamps
111  $dbr = $this->getDB( DB_REPLICA );
112  $this->startTimestamp = $dbr->timestamp( $this->getOption( 'starttime' ) );
113  $this->endTimestamp = $dbr->timestamp( $this->getOption( 'endtime' ) );
114 
115  if ( $this->startTimestamp > $this->endTimestamp ) {
116  $this->error( "\nERROR: starttime after endtime\n" );
117  $this->maybeHelp( true );
118  }
119 
120  // Turn on verbose when dry-run is enabled
121  if ( $this->hasOption( 'dry-run' ) ) {
122  $this->mOptions['verbose'] = 1;
123  }
124 
125  $this->verbose( 'Purging files that were: ' . implode( ', ', $typeList ) . "\n" );
126  foreach ( $typeList as $type ) {
127  $this->verbose( "Checking for {$type} files...\n" );
128  $this->purgeFromLogType( $type );
129  if ( !$this->hasOption( 'dry-run' ) ) {
130  $this->verbose( "...{$type} files purged.\n\n" );
131  }
132  }
133  }
134 
140  protected function purgeFromLogType( $type ) {
141  $repo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
142  $dbr = $this->getDB( DB_REPLICA );
143 
144  foreach ( self::$typeMappings[$type] as $logType => $logActions ) {
145  $this->verbose( "Scanning for {$logType}/" . implode( ',', $logActions ) . "\n" );
146 
147  $res = $dbr->select(
148  'logging',
149  [ 'log_title', 'log_timestamp', 'log_params' ],
150  [
151  'log_namespace' => NS_FILE,
152  'log_type' => $logType,
153  'log_action' => $logActions,
154  'log_timestamp >= ' . $dbr->addQuotes( $this->startTimestamp ),
155  'log_timestamp <= ' . $dbr->addQuotes( $this->endTimestamp ),
156  ],
157  __METHOD__
158  );
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  // Sanity 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->select(
217  'filearchive',
218  [ 'fa_archive_name' ],
219  [ 'fa_name' => $file->getName() ],
220  __METHOD__
221  );
222 
223  foreach ( $res as $row ) {
224  if ( $row->fa_archive_name === null ) {
225  // Was not an old version (current version names checked already)
226  continue;
227  }
228  $ofile = $repo->newFromArchiveName( $file->getTitle(), $row->fa_archive_name );
229  // If there is an orphaned storage file still there...delete it
230  if ( !$file->exists() && $repo->fileExists( $ofile->getPath() ) ) {
231  $dpath = $this->getDeletedPath( $repo, $ofile );
232  if ( $repo->fileExists( $dpath ) ) {
233  // Sanity check to avoid data loss
234  $repo->getBackend()->delete( [ 'src' => $ofile->getPath() ] );
235  $this->output( "Deleted orphan file: {$ofile->getPath()}.\n" );
236  } else {
237  $this->error( "File was not deleted: {$ofile->getPath()}.\n" );
238  }
239  }
240  $file->purgeOldThumbnails( $row->fa_archive_name );
241  }
242  }
243 
244  protected function getDeletedPath( LocalRepo $repo, LocalFile $file ) {
245  $hash = $repo->getFileSha1( $file->getPath() );
246  $key = "{$hash}.{$file->getExtension()}";
247 
248  return $repo->getDeletedHashPath( $key ) . $key;
249  }
250 
256  protected function verbose( $msg ) {
257  if ( $this->hasOption( 'verbose' ) ) {
258  $this->output( $msg );
259  }
260  }
261 }
262 
263 $maintClass = PurgeChangedFiles::class;
264 require_once RUN_MAINTENANCE_IF_MAIN;
RUN_MAINTENANCE_IF_MAIN
const RUN_MAINTENANCE_IF_MAIN
Definition: Maintenance.php:38
PurgeChangedFiles\$endTimestamp
string $endTimestamp
Definition: purgeChangedFiles.php:62
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:154
Maintenance\maybeHelp
maybeHelp( $force=false)
Maybe show the help.
Definition: Maintenance.php:1046
$maintClass
$maintClass
Definition: purgeChangedFiles.php:263
Maintenance\addDescription
addDescription( $text)
Set the description text.
Definition: Maintenance.php:327
LocalRepo\getReplicaDB
getReplicaDB()
Get a connection to the replica DB.
Definition: LocalRepo.php:469
NS_FILE
const NS_FILE
Definition: Defines.php:75
$file
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition: router.php:42
LocalFile\purgeOldThumbnails
purgeOldThumbnails( $archiveName)
Delete cached transformed files for an archived version only.
Definition: LocalFile.php:1089
PurgeChangedFiles\__construct
__construct()
Default constructor.
Definition: purgeChangedFiles.php:64
Maintenance
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
Definition: Maintenance.php:55
$res
$res
Definition: testCompression.php:57
PurgeChangedFiles\verbose
verbose( $msg)
Send an output message iff the 'verbose' option has been provided.
Definition: purgeChangedFiles.php:256
$dbr
$dbr
Definition: testCompression.php:54
PurgeChangedFiles\$typeMappings
static array $typeMappings
Mapping from type option to log type and actions.
Definition: purgeChangedFiles.php:39
Maintenance\addOption
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
Definition: Maintenance.php:245
PurgeChangedFiles\purgeFromArchiveTable
purgeFromArchiveTable(LocalRepo $repo, LocalFile $file)
Definition: purgeChangedFiles.php:214
$wgHTCPRouting
$wgHTCPRouting
Routing configuration for HTCP multicast purging.
Definition: DefaultSettings.php:3066
PurgeChangedFiles\$startTimestamp
string $startTimestamp
Definition: purgeChangedFiles.php:57
Title\makeTitle
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:592
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
FileRepo\fileExists
fileExists( $file)
Checks existence of a file.
Definition: FileRepo.php:1404
FileRepo\getFileSha1
getFileSha1( $virtualUrl)
Get the sha1 (base 36) of a file with a given virtual URL/storage path.
Definition: FileRepo.php:1637
LocalFile
Class to represent a local file in the wiki's own database.
Definition: LocalFile.php:59
LocalRepo\newFromArchiveName
newFromArchiveName( $title, $archiveName)
Definition: LocalRepo.php:86
Maintenance\getDB
getDB( $db, $groups=[], $dbDomain=false)
Returns a database to be used by current maintenance script.
Definition: Maintenance.php:1366
FileRepo\getBackend
getBackend()
Get the file backend instance.
Definition: FileRepo.php:244
PurgeChangedFiles\execute
execute()
Do the actual work.
Definition: purgeChangedFiles.php:78
PurgeChangedFiles\getDeletedPath
getDeletedPath(LocalRepo $repo, LocalFile $file)
Definition: purgeChangedFiles.php:244
PurgeChangedFiles\purgeFromLogType
purgeFromLogType( $type)
Purge cache and thumbnails for changes of the given type.
Definition: purgeChangedFiles.php:140
unserialize
unserialize( $serialized)
Definition: ApiMessageTrait.php:146
Maintenance\getOption
getOption( $name, $default=null)
Get an option, or return the default.
Definition: Maintenance.php:281
Maintenance\getBatchSize
getBatchSize()
Returns batch size.
Definition: Maintenance.php:366
Maintenance\error
error( $err, $die=0)
Throw an error to the user.
Definition: Maintenance.php:463
Maintenance\output
output( $out, $channel=null)
Throw some output to the user.
Definition: Maintenance.php:434
Maintenance\hasOption
hasOption( $name)
Checks to see if a particular option exists.
Definition: Maintenance.php:266
FileRepo\getDeletedHashPath
getDeletedHashPath( $key)
Get a relative path for a deletion archive key, e.g.
Definition: FileRepo.php:1533
PurgeChangedFiles
Maintenance script that scans the deletion log and purges affected files within a timeframe.
Definition: purgeChangedFiles.php:34
LocalRepo
A repository that stores files in the local filesystem and registers them in the wiki's own database.
Definition: LocalRepo.php:37
Maintenance\setBatchSize
setBatchSize( $s=0)
Set the batch size.
Definition: Maintenance.php:374
$type
$type
Definition: testCompression.php:52