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