MediaWiki  master
ApiQueryAllDeletedRevisions.php
Go to the documentation of this file.
1 <?php
38 
45 
47  private $revisionStore;
48 
50  private $changeTagDefStore;
51 
53  private $namespaceInfo;
54 
68  public function __construct(
69  ApiQuery $query,
70  $moduleName,
71  RevisionStore $revisionStore,
72  IContentHandlerFactory $contentHandlerFactory,
73  ParserFactory $parserFactory,
74  SlotRoleRegistry $slotRoleRegistry,
75  NameTableStore $changeTagDefStore,
76  NamespaceInfo $namespaceInfo,
77  ContentRenderer $contentRenderer,
78  ContentTransformer $contentTransformer,
79  CommentFormatter $commentFormatter
80  ) {
81  parent::__construct(
82  $query,
83  $moduleName,
84  'adr',
85  $revisionStore,
86  $contentHandlerFactory,
87  $parserFactory,
88  $slotRoleRegistry,
89  $contentRenderer,
90  $contentTransformer,
91  $commentFormatter
92  );
93  $this->revisionStore = $revisionStore;
94  $this->changeTagDefStore = $changeTagDefStore;
95  $this->namespaceInfo = $namespaceInfo;
96  }
97 
102  protected function run( ApiPageSet $resultPageSet = null ) {
103  $db = $this->getDB();
104  $params = $this->extractRequestParams( false );
105 
106  $result = $this->getResult();
107 
108  // If the user wants no namespaces, they get no pages.
109  if ( $params['namespace'] === [] ) {
110  if ( $resultPageSet === null ) {
111  $result->addValue( 'query', $this->getModuleName(), [] );
112  }
113  return;
114  }
115 
116  // This module operates in two modes:
117  // 'user': List deleted revs by a certain user
118  // 'all': List all deleted revs in NS
119  $mode = 'all';
120  if ( $params['user'] !== null ) {
121  $mode = 'user';
122  }
123 
124  if ( $mode == 'user' ) {
125  foreach ( [ 'from', 'to', 'prefix', 'excludeuser' ] as $param ) {
126  if ( $params[$param] !== null ) {
127  $p = $this->getModulePrefix();
128  $this->dieWithError(
129  [ 'apierror-invalidparammix-cannotusewith', $p . $param, "{$p}user" ],
130  'invalidparammix'
131  );
132  }
133  }
134  } else {
135  foreach ( [ 'start', 'end' ] as $param ) {
136  if ( $params[$param] !== null ) {
137  $p = $this->getModulePrefix();
138  $this->dieWithError(
139  [ 'apierror-invalidparammix-mustusewith', $p . $param, "{$p}user" ],
140  'invalidparammix'
141  );
142  }
143  }
144  }
145 
146  // If we're generating titles only, we can use DISTINCT for a better
147  // query. But we can't do that in 'user' mode (wrong index), and we can
148  // only do it when sorting ASC (because MySQL apparently can't use an
149  // index backwards for grouping even though it can for ORDER BY, WTF?)
150  $dir = $params['dir'];
151  $optimizeGenerateTitles = false;
152  if ( $mode === 'all' && $params['generatetitles'] && $resultPageSet !== null ) {
153  if ( $dir === 'newer' ) {
154  $optimizeGenerateTitles = true;
155  } else {
156  $p = $this->getModulePrefix();
157  $this->addWarning( [ 'apiwarn-alldeletedrevisions-performance', $p ], 'performance' );
158  }
159  }
160 
161  if ( $resultPageSet === null ) {
162  $this->parseParameters( $params );
163  $arQuery = $this->revisionStore->getArchiveQueryInfo();
164  $this->addTables( $arQuery['tables'] );
165  $this->addJoinConds( $arQuery['joins'] );
166  $this->addFields( $arQuery['fields'] );
167  $this->addFields( [ 'ar_title', 'ar_namespace' ] );
168  } else {
169  $this->limit = $this->getParameter( 'limit' ) ?: 10;
170  $this->addTables( 'archive' );
171  $this->addFields( [ 'ar_title', 'ar_namespace' ] );
172  if ( $optimizeGenerateTitles ) {
173  $this->addOption( 'DISTINCT' );
174  } else {
175  $this->addFields( [ 'ar_timestamp', 'ar_rev_id', 'ar_id' ] );
176  }
177  if ( $params['user'] !== null || $params['excludeuser'] !== null ) {
178  $this->addTables( 'actor' );
179  $this->addJoinConds( [ 'actor' => 'actor_id=ar_actor' ] );
180  }
181  }
182 
183  if ( $this->fld_tags ) {
184  $this->addFields( [ 'ts_tags' => ChangeTags::makeTagSummarySubquery( 'archive' ) ] );
185  }
186 
187  if ( $params['tag'] !== null ) {
188  $this->addTables( 'change_tag' );
189  $this->addJoinConds(
190  [ 'change_tag' => [ 'JOIN', [ 'ar_rev_id=ct_rev_id' ] ] ]
191  );
192  try {
193  $this->addWhereFld( 'ct_tag_id', $this->changeTagDefStore->getId( $params['tag'] ) );
194  } catch ( NameTableAccessException $exception ) {
195  // Return nothing.
196  $this->addWhere( '1=0' );
197  }
198  }
199 
200  // This means stricter restrictions
201  if ( ( $this->fld_comment || $this->fld_parsedcomment ) &&
202  !$this->getAuthority()->isAllowed( 'deletedhistory' )
203  ) {
204  $this->dieWithError( 'apierror-cantview-deleted-comment', 'permissiondenied' );
205  }
206  if ( $this->fetchContent &&
207  !$this->getAuthority()->isAllowedAny( 'deletedtext', 'undelete' )
208  ) {
209  $this->dieWithError( 'apierror-cantview-deleted-revision-content', 'permissiondenied' );
210  }
211 
212  $miser_ns = null;
213 
214  if ( $mode == 'all' ) {
215  $namespaces = $params['namespace'] ?? $this->namespaceInfo->getValidNamespaces();
216  $this->addWhereFld( 'ar_namespace', $namespaces );
217 
218  // For from/to/prefix, we have to consider the potential
219  // transformations of the title in all specified namespaces.
220  // Generally there will be only one transformation, but wikis with
221  // some namespaces case-sensitive could have two.
222  if ( $params['from'] !== null || $params['to'] !== null ) {
223  $isDirNewer = ( $dir === 'newer' );
224  $after = ( $isDirNewer ? '>=' : '<=' );
225  $before = ( $isDirNewer ? '<=' : '>=' );
226  $where = [];
227  foreach ( $namespaces as $ns ) {
228  $w = [];
229  if ( $params['from'] !== null ) {
230  $w[] = 'ar_title' . $after .
231  $db->addQuotes( $this->titlePartToKey( $params['from'], $ns ) );
232  }
233  if ( $params['to'] !== null ) {
234  $w[] = 'ar_title' . $before .
235  $db->addQuotes( $this->titlePartToKey( $params['to'], $ns ) );
236  }
237  $w = $db->makeList( $w, LIST_AND );
238  $where[$w][] = $ns;
239  }
240  if ( count( $where ) == 1 ) {
241  $where = key( $where );
242  $this->addWhere( $where );
243  } else {
244  $where2 = [];
245  foreach ( $where as $w => $ns ) {
246  $where2[] = $db->makeList( [ $w, 'ar_namespace' => $ns ], LIST_AND );
247  }
248  $this->addWhere( $db->makeList( $where2, LIST_OR ) );
249  }
250  }
251 
252  if ( isset( $params['prefix'] ) ) {
253  $where = [];
254  foreach ( $namespaces as $ns ) {
255  $w = 'ar_title' . $db->buildLike(
256  $this->titlePartToKey( $params['prefix'], $ns ),
257  $db->anyString() );
258  $where[$w][] = $ns;
259  }
260  if ( count( $where ) == 1 ) {
261  $where = key( $where );
262  $this->addWhere( $where );
263  } else {
264  $where2 = [];
265  foreach ( $where as $w => $ns ) {
266  $where2[] = $db->makeList( [ $w, 'ar_namespace' => $ns ], LIST_AND );
267  }
268  $this->addWhere( $db->makeList( $where2, LIST_OR ) );
269  }
270  }
271  } else {
272  if ( $this->getConfig()->get( MainConfigNames::MiserMode ) ) {
273  $miser_ns = $params['namespace'];
274  } else {
275  $this->addWhereFld( 'ar_namespace', $params['namespace'] );
276  }
277  $this->addTimestampWhereRange( 'ar_timestamp', $dir, $params['start'], $params['end'] );
278  }
279 
280  if ( $params['user'] !== null ) {
281  // We could get the actor ID from the ActorStore, but it's probably
282  // uncached at this point, and the non-generator case needs an actor
283  // join anyway so adding this join here is normally free. This should
284  // use the ar_actor_timestamp index.
285  $this->addWhereFld( 'actor_name', $params['user'] );
286  } elseif ( $params['excludeuser'] !== null ) {
287  $this->addWhere( 'actor_name<>' . $db->addQuotes( $params['excludeuser'] ) );
288  }
289 
290  if ( $params['user'] !== null || $params['excludeuser'] !== null ) {
291  // Paranoia: avoid brute force searches (T19342)
292  if ( !$this->getAuthority()->isAllowed( 'deletedhistory' ) ) {
293  $bitmask = RevisionRecord::DELETED_USER;
294  } elseif ( !$this->getAuthority()->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
295  $bitmask = RevisionRecord::DELETED_USER | RevisionRecord::DELETED_RESTRICTED;
296  } else {
297  $bitmask = 0;
298  }
299  if ( $bitmask ) {
300  $this->addWhere( $db->bitAnd( 'ar_deleted', $bitmask ) . " != $bitmask" );
301  }
302  }
303 
304  if ( $params['continue'] !== null ) {
305  $op = ( $dir == 'newer' ? '>=' : '<=' );
306  if ( $optimizeGenerateTitles ) {
307  $cont = $this->parseContinueParamOrDie( $params['continue'], [ 'int', 'string' ] );
308  $this->addWhere( $db->buildComparison( $op, [
309  'ar_namespace' => $cont[0],
310  'ar_title' => $cont[1],
311  ] ) );
312  } elseif ( $mode == 'all' ) {
313  $cont = $this->parseContinueParamOrDie( $params['continue'], [ 'int', 'string', 'timestamp', 'int' ] );
314  $this->addWhere( $db->buildComparison( $op, [
315  'ar_namespace' => $cont[0],
316  'ar_title' => $cont[1],
317  'ar_timestamp' => $db->timestamp( $cont[2] ),
318  'ar_id' => $cont[3],
319  ] ) );
320  } else {
321  $cont = $this->parseContinueParamOrDie( $params['continue'], [ 'timestamp', 'int' ] );
322  $this->addWhere( $db->buildComparison( $op, [
323  'ar_timestamp' => $db->timestamp( $cont[0] ),
324  'ar_id' => $cont[1],
325  ] ) );
326  }
327  }
328 
329  $this->addOption( 'LIMIT', $this->limit + 1 );
330 
331  $sort = ( $dir == 'newer' ? '' : ' DESC' );
332  $orderby = [];
333  if ( $optimizeGenerateTitles ) {
334  // Targeting index ar_name_title_timestamp
335  if ( $params['namespace'] === null || count( array_unique( $params['namespace'] ) ) > 1 ) {
336  $orderby[] = "ar_namespace $sort";
337  }
338  $orderby[] = "ar_title $sort";
339  } elseif ( $mode == 'all' ) {
340  // Targeting index ar_name_title_timestamp
341  if ( $params['namespace'] === null || count( array_unique( $params['namespace'] ) ) > 1 ) {
342  $orderby[] = "ar_namespace $sort";
343  }
344  $orderby[] = "ar_title $sort";
345  $orderby[] = "ar_timestamp $sort";
346  $orderby[] = "ar_id $sort";
347  } else {
348  // Targeting index usertext_timestamp
349  // 'user' is always constant.
350  $orderby[] = "ar_timestamp $sort";
351  $orderby[] = "ar_id $sort";
352  }
353  $this->addOption( 'ORDER BY', $orderby );
354 
355  $res = $this->select( __METHOD__ );
356 
357  if ( $resultPageSet === null ) {
358  $this->executeGenderCacheFromResultWrapper( $res, __METHOD__, 'ar' );
359  }
360 
361  $pageMap = []; // Maps ns&title to array index
362  $count = 0;
363  $nextIndex = 0;
364  $generated = [];
365  foreach ( $res as $row ) {
366  if ( ++$count > $this->limit ) {
367  // We've had enough
368  if ( $optimizeGenerateTitles ) {
369  $this->setContinueEnumParameter( 'continue', "$row->ar_namespace|$row->ar_title" );
370  } elseif ( $mode == 'all' ) {
371  $this->setContinueEnumParameter( 'continue',
372  "$row->ar_namespace|$row->ar_title|$row->ar_timestamp|$row->ar_id"
373  );
374  } else {
375  $this->setContinueEnumParameter( 'continue', "$row->ar_timestamp|$row->ar_id" );
376  }
377  break;
378  }
379 
380  // Miser mode namespace check
381  if ( $miser_ns !== null && !in_array( $row->ar_namespace, $miser_ns ) ) {
382  continue;
383  }
384 
385  if ( $resultPageSet !== null ) {
386  if ( $params['generatetitles'] ) {
387  $key = "{$row->ar_namespace}:{$row->ar_title}";
388  if ( !isset( $generated[$key] ) ) {
389  $generated[$key] = Title::makeTitle( $row->ar_namespace, $row->ar_title );
390  }
391  } else {
392  $generated[] = $row->ar_rev_id;
393  }
394  } else {
395  $revision = $this->revisionStore->newRevisionFromArchiveRow( $row );
396  $rev = $this->extractRevisionInfo( $revision, $row );
397 
398  if ( !isset( $pageMap[$row->ar_namespace][$row->ar_title] ) ) {
399  $index = $nextIndex++;
400  $pageMap[$row->ar_namespace][$row->ar_title] = $index;
401  $title = Title::newFromLinkTarget( $revision->getPageAsLinkTarget() );
402  $a = [
403  'pageid' => $title->getArticleID(),
404  'revisions' => [ $rev ],
405  ];
406  ApiResult::setIndexedTagName( $a['revisions'], 'rev' );
408  $fit = $result->addValue( [ 'query', $this->getModuleName() ], $index, $a );
409  } else {
410  $index = $pageMap[$row->ar_namespace][$row->ar_title];
411  $fit = $result->addValue(
412  [ 'query', $this->getModuleName(), $index, 'revisions' ],
413  null, $rev );
414  }
415  if ( !$fit ) {
416  if ( $mode == 'all' ) {
417  $this->setContinueEnumParameter( 'continue',
418  "$row->ar_namespace|$row->ar_title|$row->ar_timestamp|$row->ar_id"
419  );
420  } else {
421  $this->setContinueEnumParameter( 'continue', "$row->ar_timestamp|$row->ar_id" );
422  }
423  break;
424  }
425  }
426  }
427 
428  if ( $resultPageSet !== null ) {
429  if ( $params['generatetitles'] ) {
430  $resultPageSet->populateFromTitles( $generated );
431  } else {
432  $resultPageSet->populateFromRevisionIDs( $generated );
433  }
434  } else {
435  $result->addIndexedTagName( [ 'query', $this->getModuleName() ], 'page' );
436  }
437  }
438 
439  public function getAllowedParams() {
440  $ret = parent::getAllowedParams() + [
441  'user' => [
442  ParamValidator::PARAM_TYPE => 'user',
443  UserDef::PARAM_ALLOWED_USER_TYPES => [ 'name', 'ip', 'id', 'interwiki' ],
444  ],
445  'namespace' => [
446  ParamValidator::PARAM_ISMULTI => true,
447  ParamValidator::PARAM_TYPE => 'namespace',
448  ],
449  'start' => [
450  ParamValidator::PARAM_TYPE => 'timestamp',
451  ApiBase::PARAM_HELP_MSG_INFO => [ [ 'useronly' ] ],
452  ],
453  'end' => [
454  ParamValidator::PARAM_TYPE => 'timestamp',
455  ApiBase::PARAM_HELP_MSG_INFO => [ [ 'useronly' ] ],
456  ],
457  'dir' => [
458  ParamValidator::PARAM_TYPE => [
459  'newer',
460  'older'
461  ],
462  ParamValidator::PARAM_DEFAULT => 'older',
463  ApiBase::PARAM_HELP_MSG => 'api-help-param-direction',
464  ],
465  'from' => [
466  ApiBase::PARAM_HELP_MSG_INFO => [ [ 'nonuseronly' ] ],
467  ],
468  'to' => [
469  ApiBase::PARAM_HELP_MSG_INFO => [ [ 'nonuseronly' ] ],
470  ],
471  'prefix' => [
472  ApiBase::PARAM_HELP_MSG_INFO => [ [ 'nonuseronly' ] ],
473  ],
474  'excludeuser' => [
475  ParamValidator::PARAM_TYPE => 'user',
476  UserDef::PARAM_ALLOWED_USER_TYPES => [ 'name', 'ip', 'id', 'interwiki' ],
477  ApiBase::PARAM_HELP_MSG_INFO => [ [ 'nonuseronly' ] ],
478  ],
479  'tag' => null,
480  'continue' => [
481  ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
482  ],
483  'generatetitles' => [
484  ParamValidator::PARAM_DEFAULT => false
485  ],
486  ];
487 
488  if ( $this->getConfig()->get( MainConfigNames::MiserMode ) ) {
489  $ret['user'][ApiBase::PARAM_HELP_MSG_APPEND] = [
490  'apihelp-query+alldeletedrevisions-param-miser-user-namespace',
491  ];
492  $ret['namespace'][ApiBase::PARAM_HELP_MSG_APPEND] = [
493  'apihelp-query+alldeletedrevisions-param-miser-user-namespace',
494  ];
495  }
496 
497  return $ret;
498  }
499 
500  protected function getExamplesMessages() {
501  return [
502  'action=query&list=alldeletedrevisions&adruser=Example&adrlimit=50'
503  => 'apihelp-query+alldeletedrevisions-example-user',
504  'action=query&list=alldeletedrevisions&adrdir=newer&adrnamespace=0&adrlimit=50'
505  => 'apihelp-query+alldeletedrevisions-example-ns-main',
506  ];
507  }
508 
509  public function getHelpUrls() {
510  return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Alldeletedrevisions';
511  }
512 }
const LIST_OR
Definition: Defines.php:46
const LIST_AND
Definition: Defines.php:43
dieWithError( $msg, $code=null, $data=null, $httpCode=0)
Abort execution with an error.
Definition: ApiBase.php:1459
getModulePrefix()
Get parameter prefix (usually two letters or an empty string).
Definition: ApiBase.php:513
getParameter( $paramName, $parseLimit=true)
Get a value for the given parameter.
Definition: ApiBase.php:893
const PARAM_HELP_MSG_INFO
(array) Specify additional information tags for the parameter.
Definition: ApiBase.php:182
const PARAM_HELP_MSG_APPEND
((string|array|Message)[]) Specify additional i18n messages to append to the normal message for this ...
Definition: ApiBase.php:172
parseContinueParamOrDie(string $continue, array $types)
Parse the 'continue' parameter in the usual format and validate the types of each part,...
Definition: ApiBase.php:1648
getResult()
Get the result object.
Definition: ApiBase.php:636
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition: ApiBase.php:772
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition: ApiBase.php:165
addWarning( $msg, $code=null, $data=null)
Add a warning for this module.
Definition: ApiBase.php:1377
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:505
This class contains a list of pages that the client has requested.
Definition: ApiPageSet.php:52
Query module to enumerate all deleted revisions.
getExamplesMessages()
Returns usage examples for this module.
getHelpUrls()
Return links to more detailed help pages about the module.
run(ApiPageSet $resultPageSet=null)
__construct(ApiQuery $query, $moduleName, RevisionStore $revisionStore, IContentHandlerFactory $contentHandlerFactory, ParserFactory $parserFactory, SlotRoleRegistry $slotRoleRegistry, NameTableStore $changeTagDefStore, NamespaceInfo $namespaceInfo, ContentRenderer $contentRenderer, ContentTransformer $contentTransformer, CommentFormatter $commentFormatter)
static addTitleInfo(&$arr, $title, $prefix='')
Add information (title and namespace) about a Title object to a result array.
addFields( $value)
Add a set of fields to select to the internal array.
addOption( $name, $value=null)
Add an option such as LIMIT or USE INDEX.
addTables( $tables, $alias=null)
Add a set of tables to the internal array.
addTimestampWhereRange( $field, $dir, $start, $end, $sort=true)
Add a WHERE clause corresponding to a range, similar to addWhereRange, but converts $start and $end t...
getDB()
Get the Query database connection (read-only)
executeGenderCacheFromResultWrapper(IResultWrapper $res, $fname=__METHOD__, $fieldPrefix='page')
Preprocess the result set to fill the GenderCache with the necessary information before using self::a...
select( $method, $extraQuery=[], array &$hookData=null)
Execute a SELECT query based on the values in the internal arrays.
addJoinConds( $join_conds)
Add a set of JOIN conditions to the internal array.
addWhereFld( $field, $value)
Equivalent to addWhere( [ $field => $value ] )
titlePartToKey( $titlePart, $namespace=NS_MAIN)
Convert an input title or title prefix into a dbkey.
addWhere( $value)
Add a set of WHERE clauses to the internal array.
setContinueEnumParameter( $paramName, $paramValue)
Overridden to set the generator param if in generator mode.
A base class for functions common to producing a list of revisions.
parseParameters( $params)
Parse the parameters into the various instance fields.
extractRevisionInfo(RevisionRecord $revision, $row)
Extract information from the RevisionRecord.
This is the main query class.
Definition: ApiQuery.php:41
static setIndexedTagName(array &$arr, $tag)
Set the tag name for numeric-keyed values in XML format.
Definition: ApiResult.php:604
static makeTagSummarySubquery( $tables)
Make the tag summary subquery based on the given tables and return it.
This is the main service interface for converting single-line comments from various DB comment fields...
A class containing constants representing the names of configuration variables.
Page revision base class.
Service for looking up page revisions.
A registry service for SlotRoleHandlers, used to define which slot roles are available on which page.
Exception representing a failure to look up a row from a name table.
This is a utility class for dealing with namespaces that encodes all the "magic" behaviors of them ba...
static newFromLinkTarget(LinkTarget $linkTarget, $forceClone='')
Returns a Title given a LinkTarget.
Definition: Title.php:285
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:641
Service for formatting and validating API parameters.