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  if ( $typeOpt === 'all' ) {
98  // Convert 'all' to all registered types
99  $typeOpt = implode( ',', array_keys( self::$typeMappings ) );
100  }
101  $typeList = explode( ',', $typeOpt );
102  foreach ( $typeList as $type ) {
103  if ( !isset( self::$typeMappings[$type] ) ) {
104  $this->error( "\nERROR: Unknown type: {$type}\n" );
105  $this->maybeHelp( true );
106  }
107  }
108 
109  // Validate the timestamps
110  $dbr = $this->getDB( DB_REPLICA );
111  $this->startTimestamp = $dbr->timestamp( $this->getOption( 'starttime' ) );
112  $this->endTimestamp = $dbr->timestamp( $this->getOption( 'endtime' ) );
113 
114  if ( $this->startTimestamp > $this->endTimestamp ) {
115  $this->error( "\nERROR: starttime after endtime\n" );
116  $this->maybeHelp( true );
117  }
118 
119  // Turn on verbose when dry-run is enabled
120  if ( $this->hasOption( 'dry-run' ) ) {
121  $this->mOptions['verbose'] = 1;
122  }
123 
124  $this->verbose( 'Purging files that were: ' . implode( ', ', $typeList ) . "\n" );
125  foreach ( $typeList as $type ) {
126  $this->verbose( "Checking for {$type} files...\n" );
127  $this->purgeFromLogType( $type );
128  if ( !$this->hasOption( 'dry-run' ) ) {
129  $this->verbose( "...{$type} files purged.\n\n" );
130  }
131  }
132  }
133 
139  protected function purgeFromLogType( $type ) {
140  $repo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
141  $dbr = $this->getDB( DB_REPLICA );
142 
143  foreach ( self::$typeMappings[$type] as $logType => $logActions ) {
144  $this->verbose( "Scanning for {$logType}/" . implode( ',', $logActions ) . "\n" );
145 
146  $res = $dbr->select(
147  'logging',
148  [ 'log_title', 'log_timestamp', 'log_params' ],
149  [
150  'log_namespace' => NS_FILE,
151  'log_type' => $logType,
152  'log_action' => $logActions,
153  'log_timestamp >= ' . $dbr->addQuotes( $this->startTimestamp ),
154  'log_timestamp <= ' . $dbr->addQuotes( $this->endTimestamp ),
155  ],
156  __METHOD__
157  );
158 
159  $bSize = 0;
160  foreach ( $res as $row ) {
161  $file = $repo->newFile( Title::makeTitle( NS_FILE, $row->log_title ) );
162 
163  if ( $this->hasOption( 'dry-run' ) ) {
164  $this->verbose( "{$type}[{$row->log_timestamp}]: {$row->log_title}\n" );
165  continue;
166  }
167 
168  // Purge current version and its thumbnails
169  $file->purgeCache();
170  // Purge the old versions and their thumbnails
171  foreach ( $file->getHistory() as $oldFile ) {
172  $oldFile->purgeCache();
173  }
174 
175  if ( $logType === 'delete' ) {
176  // If there is an orphaned storage file... delete it
177  if ( !$file->exists() && $repo->fileExists( $file->getPath() ) ) {
178  $dpath = $this->getDeletedPath( $repo, $file );
179  if ( $repo->fileExists( $dpath ) ) {
180  // Check to avoid data loss
181  $repo->getBackend()->delete( [ 'src' => $file->getPath() ] );
182  $this->verbose( "Deleted orphan file: {$file->getPath()}.\n" );
183  } else {
184  $this->error( "File was not deleted: {$file->getPath()}.\n" );
185  }
186  }
187 
188  // Purge items from fileachive table (rows are likely here)
189  $this->purgeFromArchiveTable( $repo, $file );
190  } elseif ( $logType === 'move' ) {
191  // Purge the target file as well
192 
193  $params = unserialize( $row->log_params );
194  if ( isset( $params['4::target'] ) ) {
195  $target = $params['4::target'];
196  $targetFile = $repo->newFile( Title::makeTitle( NS_FILE, $target ) );
197  $targetFile->purgeCache();
198  $this->verbose( "Purged file {$target}; move target @{$row->log_timestamp}.\n" );
199  }
200  }
201 
202  $this->verbose( "Purged file {$row->log_title}; {$type} @{$row->log_timestamp}.\n" );
203 
204  if ( $this->hasOption( 'sleep-per-batch' ) && ++$bSize > $this->getBatchSize() ) {
205  $bSize = 0;
206  // sleep-per-batch is milliseconds, usleep wants micro seconds.
207  usleep( 1000 * (int)$this->getOption( 'sleep-per-batch' ) );
208  }
209  }
210  }
211  }
212 
213  protected function purgeFromArchiveTable( LocalRepo $repo, LocalFile $file ) {
214  $dbr = $repo->getReplicaDB();
215  $res = $dbr->select(
216  'filearchive',
217  [ 'fa_archive_name' ],
218  [ 'fa_name' => $file->getName() ],
219  __METHOD__
220  );
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 $maintClass = PurgeChangedFiles::class;
263 require_once RUN_MAINTENANCE_IF_MAIN;
const NS_FILE
Definition: Defines.php:70
fileExists( $file)
Checks existence of a file.
Definition: FileRepo.php:1432
getFileSha1( $virtualUrl)
Get the sha1 (base 36) of a file with a given virtual URL/storage path.
Definition: FileRepo.php:1660
getDeletedHashPath( $key)
Get a relative path for a deletion archive key, e.g.
Definition: FileRepo.php:1556
getBackend()
Get the file backend instance.
Definition: FileRepo.php:250
Local file in the wiki's own database.
Definition: LocalFile.php:60
purgeOldThumbnails( $archiveName)
Delete cached transformed files for an archived version only.
Definition: LocalFile.php:1370
Local repository that stores files in the local filesystem and registers them in the wiki's own datab...
Definition: LocalRepo.php:39
getReplicaDB()
Get a connection to the replica DB.
Definition: LocalRepo.php:514
newFromArchiveName( $title, $archiveName)
Definition: LocalRepo.php:127
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
Definition: Maintenance.php:66
getDB( $db, $groups=[], $dbDomain=false)
Returns a database to be used by current maintenance script.
error( $err, $die=0)
Throw an error to the user.
output( $out, $channel=null)
Throw some output to the user.
hasOption( $name)
Checks to see if a particular option was set.
getBatchSize()
Returns batch size.
addDescription( $text)
Set the description text.
maybeHelp( $force=false)
Maybe show the help.
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
getOption( $name, $default=null)
Get an option, or return the default.
setBatchSize( $s=0)
Service locator for MediaWiki core services.
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.
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:641
$wgHTCPRouting
Config variable stub for the HTCPRouting setting, for use by phpdoc and IDEs.
const DB_REPLICA
Definition: defines.php:26
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition: router.php:42