MediaWiki  REL1_31
Go to the documentation of this file.
1 <?php
19 require_once __DIR__ . '/Maintenance.php';
28  public function __construct() {
29  parent::__construct();
30  $this->addDescription( 'Remove autopatrol logs in the logging table' );
31  $this->addOption( 'dry-run', 'Print debug info instead of actually deleting' );
32  $this->addOption(
33  'check-old',
34  'Check old patrol logs (for deleting old format autopatrols).' .
35  'Note that this will not delete rows older than 2011 (MediaWiki 1.18).'
36  );
37  $this->addOption(
38  'before',
39  'Timestamp to delete only before that time, all MediaWiki timestamp formats are accepted',
40  false,
41  true
42  );
43  $this->addOption(
44  'from-id',
45  'First row (log id) to start updating from',
46  false,
47  true
48  );
49  $this->addOption(
50  'sleep',
51  'Sleep time (in seconds) between every batch',
52  false,
53  true
54  );
55  $this->setBatchSize( 1000 );
56  }
58  public function execute() {
59  $this->setBatchSize( $this->getOption( 'batch-size', $this->getBatchSize() ) );
61  $sleep = (int)$this->getOption( 'sleep', 10 );
62  $fromId = $this->getOption( 'from-id', null );
63  $this->countDown( 5 );
64  while ( true ) {
65  if ( $this->hasOption( 'check-old' ) ) {
66  $rowsData = $this->getRowsOld( $fromId );
67  // We reached end of the table
68  if ( !$rowsData ) {
69  break;
70  }
71  $rows = $rowsData['rows'];
72  $fromId = $rowsData['lastId'];
74  // There is nothing to delete in this batch
75  if ( !$rows ) {
76  continue;
77  }
78  } else {
79  $rows = $this->getRows( $fromId );
80  if ( !$rows ) {
81  break;
82  }
83  $fromId = end( $rows );
84  }
86  if ( $this->hasOption( 'dry-run' ) ) {
87  $this->output( 'These rows will get deleted: ' . implode( ', ', $rows ) . "\n" );
88  } else {
89  $this->deleteRows( $rows );
90  $this->output( 'Processed up to row id ' . end( $rows ) . "\n" );
91  }
93  if ( $sleep > 0 ) {
94  sleep( $sleep );
95  }
96  }
97  }
99  private function getRows( $fromId ) {
100  $dbr = MediaWiki\MediaWikiServices::getInstance()->getDBLoadBalancer()->getConnection(
102  );
103  $before = $this->getOption( 'before', false );
105  $conds = [
106  'log_type' => 'patrol',
107  'log_action' => 'autopatrol',
108  ];
110  if ( $fromId ) {
111  $conds[] = 'log_id > ' . $dbr->addQuotes( $fromId );
112  }
114  if ( $before ) {
115  $conds[] = 'log_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $before ) );
116  }
118  return $dbr->selectFieldValues(
119  'logging',
120  'log_id',
121  $conds,
122  __METHOD__,
123  [ 'LIMIT' => $this->getBatchSize() ]
124  );
125  }
127  private function getRowsOld( $fromId ) {
128  $dbr = MediaWiki\MediaWikiServices::getInstance()->getDBLoadBalancer()->getConnection(
130  );
131  $batchSize = $this->getBatchSize();
132  $before = $this->getOption( 'before', false );
134  $conds = [
135  'log_type' => 'patrol',
136  'log_action' => 'patrol',
137  ];
139  if ( $fromId ) {
140  $conds[] = 'log_id > ' . $dbr->addQuotes( $fromId );
141  }
143  if ( $before ) {
144  $conds[] = 'log_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $before ) );
145  }
147  $result = $dbr->select(
148  'logging',
149  [ 'log_id', 'log_params' ],
150  $conds,
151  __METHOD__,
152  [ 'LIMIT' => $batchSize ]
153  );
155  $last = null;
156  $autopatrols = [];
157  foreach ( $result as $row ) {
158  $last = $row->log_id;
159  Wikimedia\suppressWarnings();
160  $params = unserialize( $row->log_params );
161  Wikimedia\restoreWarnings();
163  // Skipping really old rows, before 2011
164  if ( !is_array( $params ) || !array_key_exists( '6::auto', $params ) ) {
165  continue;
166  }
168  $auto = $params['6::auto'];
169  if ( $auto ) {
170  $autopatrols[] = $row->log_id;
171  }
172  }
174  if ( $last === null ) {
175  return null;
176  }
178  return [ 'rows' => $autopatrols, 'lastId' => $last ];
179  }
181  private function deleteRows( array $rows ) {
182  $dbw = MediaWiki\MediaWikiServices::getInstance()->getDBLoadBalancer()->getConnection(
184  );
186  $dbw->delete(
187  'logging',
188  [ 'log_id' => $rows ],
189  __METHOD__
190  );
192  MediaWiki\MediaWikiServices::getInstance()->getDBLoadBalancerFactory()->waitForReplication();
193  }
195 }
198 require_once RUN_MAINTENANCE_IF_MAIN;
getRows( $fromId)
Definition: deleteAutoPatrolLogs.php:99
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction $rows
Definition: hooks.txt:2783
the array() calling protocol came about after MediaWiki 1.4rc1.
Definition: profileinfo.php:408
addDescription( $text)
Set the description text.
Definition: Maintenance.php:291
This program is free software; you can redistribute it and/or modify it under the terms of the GNU Ge...
Definition: deleteAutoPatrolLogs.php:26
unserialize( $serialized)
Definition: ApiMessage.php:192
Definition: maintenance.txt:50
Definition: styleTest.css.php:40
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
Definition: maintenance.txt:39
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\d*-\d*)") will be honored when streaming the file. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1993
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:37
Definition: testCompression.php:50
Do the actual work.
Definition: deleteAutoPatrolLogs.php:58
Default constructor.
Definition: deleteAutoPatrolLogs.php:28
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
Definition: Maintenance.php:219
Definition: defines.php:25
Definition: defines.php:29
countDown( $seconds)
Count down from $seconds to zero on the terminal, with a one-second pause between showing each number...
Definition: Maintenance.php:1487
static getInstance()
Returns the global default instance of the top level service locator.
Definition: MediaWikiServices.php:109
getRowsOld( $fromId)
Definition: deleteAutoPatrolLogs.php:127
getOption( $name, $default=null)
Get an option, or return the default.
Definition: Maintenance.php:254
Returns batch size.
Definition: Maintenance.php:321
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:22
Definition: deleteAutoPatrolLogs.php:197
output( $out, $channel=null)
Throw some output to the user.
Definition: Maintenance.php:388
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:56
hasOption( $name)
Checks to see if a particular param exists.
Definition: Maintenance.php:240
return true to allow those checks to and false if checking is done remove or add to the links of a group of changes in EnhancedChangesList Hook subscribers can return false to omit this line from recentchanges use this to change the tables headers change it to an object instance and return false override the list derivative used the name of the old file when set the default code will be skipped true if there is text before this autocomment $auto
Definition: hooks.txt:1587
deleteRows(array $rows)
Definition: deleteAutoPatrolLogs.php:181
setBatchSize( $s=0)
Set the batch size.
Definition: Maintenance.php:329