purgeChangedFiles.php 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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. require_once __DIR__ . '/Maintenance.php';
  24. /**
  25. * Maintenance script that scans the deletion log and purges affected files
  26. * within a timeframe.
  27. *
  28. * @ingroup Maintenance
  29. */
  30. class PurgeChangedFiles extends Maintenance {
  31. /**
  32. * Mapping from type option to log type and actions.
  33. * @var array
  34. */
  35. private static $typeMappings = [
  36. 'created' => [
  37. 'upload' => [ 'upload' ],
  38. 'import' => [ 'upload', 'interwiki' ],
  39. ],
  40. 'deleted' => [
  41. 'delete' => [ 'delete', 'revision' ],
  42. 'suppress' => [ 'delete', 'revision' ],
  43. ],
  44. 'modified' => [
  45. 'upload' => [ 'overwrite', 'revert' ],
  46. 'move' => [ 'move', 'move_redir' ],
  47. ],
  48. ];
  49. /**
  50. * @var string
  51. */
  52. private $startTimestamp;
  53. /**
  54. * @var string
  55. */
  56. private $endTimestamp;
  57. public function __construct() {
  58. parent::__construct();
  59. $this->addDescription( 'Scan the logging table and purge files and thumbnails.' );
  60. $this->addOption( 'starttime', 'Starting timestamp', true, true );
  61. $this->addOption( 'endtime', 'Ending timestamp', true, true );
  62. $this->addOption( 'type', 'Comma-separated list of types of changes to send purges for (' .
  63. implode( ',', array_keys( self::$typeMappings ) ) . ',all)', false, true );
  64. $this->addOption( 'htcp-dest', 'HTCP announcement destination (IP:port)', false, true );
  65. $this->addOption( 'dry-run', 'Do not send purge requests' );
  66. $this->addOption( 'sleep-per-batch', 'Milliseconds to sleep between batches', false, true );
  67. $this->addOption( 'verbose', 'Show more output', false, false, 'v' );
  68. $this->setBatchSize( 100 );
  69. }
  70. public function execute() {
  71. global $wgHTCPRouting;
  72. if ( $this->hasOption( 'htcp-dest' ) ) {
  73. $parts = explode( ':', $this->getOption( 'htcp-dest' ) );
  74. if ( count( $parts ) < 2 ) {
  75. // Add default htcp port
  76. $parts[] = '4827';
  77. }
  78. // Route all HTCP messages to provided host:port
  79. $wgHTCPRouting = [
  80. '' => [ 'host' => $parts[0], 'port' => $parts[1] ],
  81. ];
  82. $this->verbose( "HTCP broadcasts to {$parts[0]}:{$parts[1]}\n" );
  83. }
  84. // Find out which actions we should be concerned with
  85. $typeOpt = $this->getOption( 'type', 'all' );
  86. $validTypes = array_keys( self::$typeMappings );
  87. if ( $typeOpt === 'all' ) {
  88. // Convert 'all' to all registered types
  89. $typeOpt = implode( ',', $validTypes );
  90. }
  91. $typeList = explode( ',', $typeOpt );
  92. foreach ( $typeList as $type ) {
  93. if ( !in_array( $type, $validTypes ) ) {
  94. $this->error( "\nERROR: Unknown type: {$type}\n" );
  95. $this->maybeHelp( true );
  96. }
  97. }
  98. // Validate the timestamps
  99. $dbr = $this->getDB( DB_SLAVE );
  100. $this->startTimestamp = $dbr->timestamp( $this->getOption( 'starttime' ) );
  101. $this->endTimestamp = $dbr->timestamp( $this->getOption( 'endtime' ) );
  102. if ( $this->startTimestamp > $this->endTimestamp ) {
  103. $this->error( "\nERROR: starttime after endtime\n" );
  104. $this->maybeHelp( true );
  105. }
  106. // Turn on verbose when dry-run is enabled
  107. if ( $this->hasOption( 'dry-run' ) ) {
  108. $this->mOptions['verbose'] = 1;
  109. }
  110. $this->verbose( 'Purging files that were: ' . implode( ', ', $typeList ) . "\n" );
  111. foreach ( $typeList as $type ) {
  112. $this->verbose( "Checking for {$type} files...\n" );
  113. $this->purgeFromLogType( $type );
  114. if ( !$this->hasOption( 'dry-run' ) ) {
  115. $this->verbose( "...{$type} files purged.\n\n" );
  116. }
  117. }
  118. }
  119. /**
  120. * Purge cache and thumbnails for changes of the given type.
  121. *
  122. * @param string $type Type of change to find
  123. */
  124. protected function purgeFromLogType( $type ) {
  125. $repo = RepoGroup::singleton()->getLocalRepo();
  126. $dbr = $this->getDB( DB_SLAVE );
  127. foreach ( self::$typeMappings[$type] as $logType => $logActions ) {
  128. $this->verbose( "Scanning for {$logType}/" . implode( ',', $logActions ) . "\n" );
  129. $res = $dbr->select(
  130. 'logging',
  131. [ 'log_title', 'log_timestamp', 'log_params' ],
  132. [
  133. 'log_namespace' => NS_FILE,
  134. 'log_type' => $logType,
  135. 'log_action' => $logActions,
  136. 'log_timestamp >= ' . $dbr->addQuotes( $this->startTimestamp ),
  137. 'log_timestamp <= ' . $dbr->addQuotes( $this->endTimestamp ),
  138. ],
  139. __METHOD__
  140. );
  141. $bSize = 0;
  142. foreach ( $res as $row ) {
  143. $file = $repo->newFile( Title::makeTitle( NS_FILE, $row->log_title ) );
  144. if ( $this->hasOption( 'dry-run' ) ) {
  145. $this->verbose( "{$type}[{$row->log_timestamp}]: {$row->log_title}\n" );
  146. continue;
  147. }
  148. // Purge current version and any versions in oldimage table
  149. $file->purgeCache();
  150. if ( $logType === 'delete' ) {
  151. // If there is an orphaned storage file... delete it
  152. if ( !$file->exists() && $repo->fileExists( $file->getPath() ) ) {
  153. $dpath = $this->getDeletedPath( $repo, $file );
  154. if ( $repo->fileExists( $dpath ) ) {
  155. // Sanity check to avoid data loss
  156. $repo->getBackend()->delete( [ 'src' => $file->getPath() ] );
  157. $this->verbose( "Deleted orphan file: {$file->getPath()}.\n" );
  158. } else {
  159. $this->error( "File was not deleted: {$file->getPath()}.\n" );
  160. }
  161. }
  162. // Purge items from fileachive table (rows are likely here)
  163. $this->purgeFromArchiveTable( $repo, $file );
  164. } elseif ( $logType === 'move' ) {
  165. // Purge the target file as well
  166. $params = unserialize( $row->log_params );
  167. if ( isset( $params['4::target'] ) ) {
  168. $target = $params['4::target'];
  169. $targetFile = $repo->newFile( Title::makeTitle( NS_FILE, $target ) );
  170. $targetFile->purgeCache();
  171. $this->verbose( "Purged file {$target}; move target @{$row->log_timestamp}.\n" );
  172. }
  173. }
  174. $this->verbose( "Purged file {$row->log_title}; {$type} @{$row->log_timestamp}.\n" );
  175. if ( $this->hasOption( 'sleep-per-batch' ) && ++$bSize > $this->mBatchSize ) {
  176. $bSize = 0;
  177. // sleep-per-batch is milliseconds, usleep wants micro seconds.
  178. usleep( 1000 * (int)$this->getOption( 'sleep-per-batch' ) );
  179. }
  180. }
  181. }
  182. }
  183. protected function purgeFromArchiveTable( LocalRepo $repo, LocalFile $file ) {
  184. $dbr = $repo->getSlaveDB();
  185. $res = $dbr->select(
  186. 'filearchive',
  187. [ 'fa_archive_name' ],
  188. [ 'fa_name' => $file->getName() ],
  189. __METHOD__
  190. );
  191. foreach ( $res as $row ) {
  192. if ( $row->fa_archive_name === null ) {
  193. // Was not an old version (current version names checked already)
  194. continue;
  195. }
  196. $ofile = $repo->newFromArchiveName( $file->getTitle(), $row->fa_archive_name );
  197. // If there is an orphaned storage file still there...delete it
  198. if ( !$file->exists() && $repo->fileExists( $ofile->getPath() ) ) {
  199. $dpath = $this->getDeletedPath( $repo, $ofile );
  200. if ( $repo->fileExists( $dpath ) ) {
  201. // Sanity check to avoid data loss
  202. $repo->getBackend()->delete( [ 'src' => $ofile->getPath() ] );
  203. $this->output( "Deleted orphan file: {$ofile->getPath()}.\n" );
  204. } else {
  205. $this->error( "File was not deleted: {$ofile->getPath()}.\n" );
  206. }
  207. }
  208. $file->purgeOldThumbnails( $row->fa_archive_name );
  209. }
  210. }
  211. protected function getDeletedPath( LocalRepo $repo, LocalFile $file ) {
  212. $hash = $repo->getFileSha1( $file->getPath() );
  213. $key = "{$hash}.{$file->getExtension()}";
  214. return $repo->getDeletedHashPath( $key ) . $key;
  215. }
  216. /**
  217. * Send an output message iff the 'verbose' option has been provided.
  218. *
  219. * @param string $msg Message to output
  220. */
  221. protected function verbose( $msg ) {
  222. if ( $this->hasOption( 'verbose' ) ) {
  223. $this->output( $msg );
  224. }
  225. }
  226. }
  227. $maintClass = "PurgeChangedFiles";
  228. require_once RUN_MAINTENANCE_IF_MAIN;