MediaWiki  master
ApiQueryDeletedRevisions.php
Go to the documentation of this file.
1 <?php
29 
36 
37  public function __construct( ApiQuery $query, $moduleName ) {
38  parent::__construct( $query, $moduleName, 'drv' );
39  }
40 
41  protected function run( ApiPageSet $resultPageSet = null ) {
42  $user = $this->getUser();
43  // Before doing anything at all, let's check permissions
44  $this->checkUserRightsAny( 'deletedhistory' );
45 
46  $pageSet = $this->getPageSet();
47  $pageMap = $pageSet->getGoodAndMissingTitlesByNamespace();
48  $pageCount = count( $pageSet->getGoodAndMissingTitles() );
49  $revCount = $pageSet->getRevisionCount();
50  if ( $revCount === 0 && $pageCount === 0 ) {
51  // Nothing to do
52  return;
53  }
54  if ( $revCount !== 0 && count( $pageSet->getDeletedRevisionIDs() ) === 0 ) {
55  // Nothing to do, revisions were supplied but none are deleted
56  return;
57  }
58 
59  $params = $this->extractRequestParams( false );
60 
61  $db = $this->getDB();
62  $revisionStore = MediaWikiServices::getInstance()->getRevisionStore();
63 
64  $this->requireMaxOneParameter( $params, 'user', 'excludeuser' );
65 
66  if ( $resultPageSet === null ) {
67  $this->parseParameters( $params );
68  $arQuery = $revisionStore->getArchiveQueryInfo();
69  $this->addTables( $arQuery['tables'] );
70  $this->addFields( $arQuery['fields'] );
71  $this->addJoinConds( $arQuery['joins'] );
72  $this->addFields( [ 'ar_title', 'ar_namespace' ] );
73  } else {
74  $this->limit = $this->getParameter( 'limit' ) ?: 10;
75  $this->addTables( 'archive' );
76  $this->addFields( [ 'ar_title', 'ar_namespace', 'ar_timestamp', 'ar_rev_id', 'ar_id' ] );
77  }
78 
79  if ( $this->fld_tags ) {
80  $this->addFields( [ 'ts_tags' => ChangeTags::makeTagSummarySubquery( 'archive' ) ] );
81  }
82 
83  if ( !is_null( $params['tag'] ) ) {
84  $this->addTables( 'change_tag' );
85  $this->addJoinConds(
86  [ 'change_tag' => [ 'JOIN', [ 'ar_rev_id=ct_rev_id' ] ] ]
87  );
88  $changeTagDefStore = MediaWikiServices::getInstance()->getChangeTagDefStore();
89  try {
90  $this->addWhereFld( 'ct_tag_id', $changeTagDefStore->getId( $params['tag'] ) );
91  } catch ( NameTableAccessException $exception ) {
92  // Return nothing.
93  $this->addWhere( '1=0' );
94  }
95  }
96 
97  // This means stricter restrictions
98  if ( $this->fetchContent ) {
99  $this->checkUserRightsAny( [ 'deletedtext', 'undelete' ] );
100  }
101 
102  $dir = $params['dir'];
103 
104  if ( $revCount !== 0 ) {
105  $this->addWhere( [
106  'ar_rev_id' => array_keys( $pageSet->getDeletedRevisionIDs() )
107  ] );
108  } else {
109  // We need a custom WHERE clause that matches all titles.
110  $lb = new LinkBatch( $pageSet->getGoodAndMissingTitles() );
111  $where = $lb->constructSet( 'ar', $db );
112  $this->addWhere( $where );
113  }
114 
115  if ( !is_null( $params['user'] ) ) {
116  // Don't query by user ID here, it might be able to use the ar_usertext_timestamp index.
117  $actorQuery = ActorMigration::newMigration()
118  ->getWhere( $db, 'ar_user', User::newFromName( $params['user'], false ), false );
119  $this->addTables( $actorQuery['tables'] );
120  $this->addJoinConds( $actorQuery['joins'] );
121  $this->addWhere( $actorQuery['conds'] );
122  } elseif ( !is_null( $params['excludeuser'] ) ) {
123  // Here there's no chance of using ar_usertext_timestamp.
124  $actorQuery = ActorMigration::newMigration()
125  ->getWhere( $db, 'ar_user', User::newFromName( $params['excludeuser'], false ) );
126  $this->addTables( $actorQuery['tables'] );
127  $this->addJoinConds( $actorQuery['joins'] );
128  $this->addWhere( 'NOT(' . $actorQuery['conds'] . ')' );
129  }
130 
131  if ( !is_null( $params['user'] ) || !is_null( $params['excludeuser'] ) ) {
132  // Paranoia: avoid brute force searches (T19342)
133  // (shouldn't be able to get here without 'deletedhistory', but
134  // check it again just in case)
135  if ( !$user->isAllowed( 'deletedhistory' ) ) {
136  $bitmask = RevisionRecord::DELETED_USER;
137  } elseif ( !$user->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
138  $bitmask = RevisionRecord::DELETED_USER | RevisionRecord::DELETED_RESTRICTED;
139  } else {
140  $bitmask = 0;
141  }
142  if ( $bitmask ) {
143  $this->addWhere( $db->bitAnd( 'ar_deleted', $bitmask ) . " != $bitmask" );
144  }
145  }
146 
147  if ( !is_null( $params['continue'] ) ) {
148  $cont = explode( '|', $params['continue'] );
149  $op = ( $dir == 'newer' ? '>' : '<' );
150  if ( $revCount !== 0 ) {
151  $this->dieContinueUsageIf( count( $cont ) != 2 );
152  $rev = (int)$cont[0];
153  $this->dieContinueUsageIf( strval( $rev ) !== $cont[0] );
154  $ar_id = (int)$cont[1];
155  $this->dieContinueUsageIf( strval( $ar_id ) !== $cont[1] );
156  $this->addWhere( "ar_rev_id $op $rev OR " .
157  "(ar_rev_id = $rev AND " .
158  "ar_id $op= $ar_id)" );
159  } else {
160  $this->dieContinueUsageIf( count( $cont ) != 4 );
161  $ns = (int)$cont[0];
162  $this->dieContinueUsageIf( strval( $ns ) !== $cont[0] );
163  $title = $db->addQuotes( $cont[1] );
164  $ts = $db->addQuotes( $db->timestamp( $cont[2] ) );
165  $ar_id = (int)$cont[3];
166  $this->dieContinueUsageIf( strval( $ar_id ) !== $cont[3] );
167  $this->addWhere( "ar_namespace $op $ns OR " .
168  "(ar_namespace = $ns AND " .
169  "(ar_title $op $title OR " .
170  "(ar_title = $title AND " .
171  "(ar_timestamp $op $ts OR " .
172  "(ar_timestamp = $ts AND " .
173  "ar_id $op= $ar_id)))))" );
174  }
175  }
176 
177  $this->addOption( 'LIMIT', $this->limit + 1 );
178 
179  if ( $revCount !== 0 ) {
180  // Sort by ar_rev_id when querying by ar_rev_id
181  $this->addWhereRange( 'ar_rev_id', $dir, null, null );
182  } else {
183  // Sort by ns and title in the same order as timestamp for efficiency
184  // But only when not already unique in the query
185  if ( count( $pageMap ) > 1 ) {
186  $this->addWhereRange( 'ar_namespace', $dir, null, null );
187  }
188  $oneTitle = key( reset( $pageMap ) );
189  foreach ( $pageMap as $pages ) {
190  if ( count( $pages ) > 1 || key( $pages ) !== $oneTitle ) {
191  $this->addWhereRange( 'ar_title', $dir, null, null );
192  break;
193  }
194  }
195  $this->addTimestampWhereRange( 'ar_timestamp', $dir, $params['start'], $params['end'] );
196  }
197  // Include in ORDER BY for uniqueness
198  $this->addWhereRange( 'ar_id', $dir, null, null );
199 
200  $res = $this->select( __METHOD__ );
201  $count = 0;
202  $generated = [];
203  foreach ( $res as $row ) {
204  if ( ++$count > $this->limit ) {
205  // We've had enough
206  $this->setContinueEnumParameter( 'continue',
207  $revCount
208  ? "$row->ar_rev_id|$row->ar_id"
209  : "$row->ar_namespace|$row->ar_title|$row->ar_timestamp|$row->ar_id"
210  );
211  break;
212  }
213 
214  if ( $resultPageSet !== null ) {
215  $generated[] = $row->ar_rev_id;
216  } else {
217  if ( !isset( $pageMap[$row->ar_namespace][$row->ar_title] ) ) {
218  // Was it converted?
219  $title = Title::makeTitle( $row->ar_namespace, $row->ar_title );
220  $converted = $pageSet->getConvertedTitles();
221  if ( $title && isset( $converted[$title->getPrefixedText()] ) ) {
222  $title = Title::newFromText( $converted[$title->getPrefixedText()] );
223  if ( $title && isset( $pageMap[$title->getNamespace()][$title->getDBkey()] ) ) {
224  $pageMap[$row->ar_namespace][$row->ar_title] =
225  $pageMap[$title->getNamespace()][$title->getDBkey()];
226  }
227  }
228  }
229  if ( !isset( $pageMap[$row->ar_namespace][$row->ar_title] ) ) {
231  __METHOD__,
232  "Found row in archive (ar_id={$row->ar_id}) that didn't get processed by ApiPageSet"
233  );
234  }
235 
236  $fit = $this->addPageSubItem(
237  $pageMap[$row->ar_namespace][$row->ar_title],
238  $this->extractRevisionInfo( $revisionStore->newRevisionFromArchiveRow( $row ), $row ),
239  'rev'
240  );
241  if ( !$fit ) {
242  $this->setContinueEnumParameter( 'continue',
243  $revCount
244  ? "$row->ar_rev_id|$row->ar_id"
245  : "$row->ar_namespace|$row->ar_title|$row->ar_timestamp|$row->ar_id"
246  );
247  break;
248  }
249  }
250  }
251 
252  if ( $resultPageSet !== null ) {
253  $resultPageSet->populateFromRevisionIDs( $generated );
254  }
255  }
256 
257  public function getAllowedParams() {
258  return parent::getAllowedParams() + [
259  'start' => [
260  ApiBase::PARAM_TYPE => 'timestamp',
261  ],
262  'end' => [
263  ApiBase::PARAM_TYPE => 'timestamp',
264  ],
265  'dir' => [
267  'newer',
268  'older'
269  ],
270  ApiBase::PARAM_DFLT => 'older',
271  ApiBase::PARAM_HELP_MSG => 'api-help-param-direction',
272  ],
273  'tag' => null,
274  'user' => [
275  ApiBase::PARAM_TYPE => 'user'
276  ],
277  'excludeuser' => [
278  ApiBase::PARAM_TYPE => 'user'
279  ],
280  'continue' => [
281  ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
282  ],
283  ];
284  }
285 
286  protected function getExamplesMessages() {
287  return [
288  'action=query&prop=deletedrevisions&titles=Main%20Page|Talk:Main%20Page&' .
289  'drvslots=*&drvprop=user|comment|content'
290  => 'apihelp-query+deletedrevisions-example-titles',
291  'action=query&prop=deletedrevisions&revids=123456'
292  => 'apihelp-query+deletedrevisions-example-revids',
293  ];
294  }
295 
296  public function getHelpUrls() {
297  return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Deletedrevisions';
298  }
299 }
select( $method, $extraQuery=[], array &$hookData=null)
Execute a SELECT query based on the values in the internal arrays.
Query module to enumerate deleted revisions for pages.
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below...
Definition: ApiBase.php:94
getDB()
Get the Query database connection (read-only)
null for the local wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify $query
Definition: hooks.txt:1566
addJoinConds( $join_conds)
Add a set of JOIN conditions to the internal array.
This class contains a list of pages that the client has requested.
Definition: ApiPageSet.php:40
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition: ApiBase.php:55
Exception representing a failure to look up a row from a name table.
A base class for functions common to producing a list of revisions.
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user...
Definition: ApiBase.php:761
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation use $formDescriptor instead default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message key
Definition: hooks.txt:2138
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 MediaWikiServices
Definition: injection.txt:23
setContinueEnumParameter( $paramName, $paramValue)
Overridden to set the generator param if in generator mode.
getParameter( $paramName, $parseLimit=true)
Get a value for the given parameter.
Definition: ApiBase.php:876
Class representing a list of titles The execute() method checks them all for existence and adds them ...
Definition: LinkBatch.php:34
addPageSubItem( $pageId, $item, $elemname=null)
Same as addPageSubItems(), but one element of $data at a time.
static newMigration()
Static constructor.
addTables( $tables, $alias=null)
Add a set of tables to the internal array.
$res
Definition: database.txt:21
dieContinueUsageIf( $condition)
Die with the &#39;badcontinue&#39; error.
Definition: ApiBase.php:2200
$params
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:767
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:912
addFields( $value)
Add a set of fields to select to the internal array.
This is the main query class.
Definition: ApiQuery.php:36
presenting them properly to the user as errors is done by the caller return true use this to change the list i e etc $rev
Definition: hooks.txt:1747
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:9
requireMaxOneParameter( $params, $required)
Die if more than one of a certain set of parameters is set and not false.
Definition: ApiBase.php:931
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter...
Definition: ApiBase.php:131
__construct(ApiQuery $query, $moduleName)
addTimestampWhereRange( $field, $dir, $start, $end, $sort=true)
Add a WHERE clause corresponding to a range, similar to addWhereRange, but converts $start and $end t...
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:590
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:35
addWhere( $value)
Add a set of WHERE clauses to the internal array.
static dieDebug( $method, $message)
Internal code errors should be reported with this method.
Definition: ApiBase.php:2212
run(ApiPageSet $resultPageSet=null)
addWhereFld( $field, $value)
Equivalent to addWhere( [ $field => $value ] )
addOption( $name, $value=null)
Add an option such as LIMIT or USE INDEX.
parseParameters( $params)
Parse the parameters into the various instance fields.
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition: User.php:535
static makeTagSummarySubquery( $tables)
Make the tag summary subquery based on the given tables and return it.
Definition: ChangeTags.php:821
getPageSet()
Get the PageSet object to work on.
checkUserRightsAny( $rights, $user=null)
Helper function for permission-denied errors.
Definition: ApiBase.php:2124
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1454
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:320
addWhereRange( $field, $dir, $start, $end, $sort=true)
Add a WHERE clause corresponding to a range, and an ORDER BY clause to sort in the right direction...