MediaWiki master
ApiQueryAllRevisions.php
Go to the documentation of this file.
1<?php
9namespace MediaWiki\Api;
10
28
36
37 public function __construct(
38 ApiQuery $query,
39 string $moduleName,
40 private readonly RevisionStore $revisionStore,
41 IContentHandlerFactory $contentHandlerFactory,
42 ParserFactory $parserFactory,
43 SlotRoleRegistry $slotRoleRegistry,
44 private readonly ActorMigration $actorMigration,
45 private readonly NamespaceInfo $namespaceInfo,
46 private readonly ChangeTagsStore $changeTagsStore,
47 ContentRenderer $contentRenderer,
48 ContentTransformer $contentTransformer,
49 CommentFormatter $commentFormatter,
50 TempUserCreator $tempUserCreator,
51 UserFactory $userFactory,
52 ) {
53 parent::__construct(
54 $query,
55 $moduleName,
56 'arv',
57 $revisionStore,
58 $contentHandlerFactory,
59 $parserFactory,
60 $slotRoleRegistry,
61 $contentRenderer,
62 $contentTransformer,
63 $commentFormatter,
64 $tempUserCreator,
65 $userFactory
66 );
67 }
68
73 protected function run( ?ApiPageSet $resultPageSet = null ) {
74 $db = $this->getDB();
75 $params = $this->extractRequestParams( false );
76
77 $result = $this->getResult();
78
79 $this->requireMaxOneParameter( $params, 'user', 'excludeuser' );
80
81 $tsField = 'rev_timestamp';
82 $idField = 'rev_id';
83 $pageField = 'rev_page';
84
85 // Namespace check is likely to be desired, but can't be done
86 // efficiently in SQL.
87 $miser_ns = null;
88 $needPageTable = false;
89 if ( $params['namespace'] !== null ) {
90 $params['namespace'] = array_unique( $params['namespace'] );
91 sort( $params['namespace'] );
92 if ( $params['namespace'] != $this->namespaceInfo->getValidNamespaces() ) {
93 $needPageTable = true;
94 if ( $this->getConfig()->get( MainConfigNames::MiserMode ) ) {
95 $miser_ns = $params['namespace'];
96 } else {
97 $this->addWhere( [ 'page_namespace' => $params['namespace'] ] );
98 }
99 }
100 }
101
102 if ( $resultPageSet === null ) {
103 $this->parseParameters( $params );
104 $queryBuilder = $this->revisionStore->newSelectQueryBuilder( $db )
105 ->joinComment()
106 ->joinPage();
107 $this->getQueryBuilder()->merge( $queryBuilder );
108 } else {
109 $this->limit = $this->getParameter( 'limit' ) ?: 10;
110 $this->addTables( [ 'revision' ] );
111 $this->addFields( [ 'rev_timestamp', 'rev_id' ] );
112
113 if ( $params['generatetitles'] ) {
114 $this->addFields( [ 'rev_page' ] );
115 }
116
117 if ( $params['user'] !== null || $params['excludeuser'] !== null ) {
118 $this->getQueryBuilder()->join( 'actor', 'actor_rev_user', 'actor_rev_user.actor_id = rev_actor' );
119 }
120
121 if ( $needPageTable ) {
122 $this->getQueryBuilder()->join( 'page', null, [ "$pageField = page_id" ] );
123 if ( (bool)$miser_ns ) {
124 $this->addFields( [ 'page_namespace' ] );
125 }
126 }
127 }
128
129 // Seems to be needed to avoid a planner bug (T113901)
130 $this->addOption( 'STRAIGHT_JOIN' );
131
132 $dir = $params['dir'];
133 $this->addTimestampWhereRange( $tsField, $dir, $params['start'], $params['end'] );
134
135 if ( $this->fld_tags ) {
136 $this->addFields( [
137 'ts_tags' => $this->changeTagsStore->makeTagSummarySubquery( 'revision' )
138 ] );
139 }
140
141 if ( $params['user'] !== null ) {
142 $actorQuery = $this->actorMigration->getWhere( $db, 'rev_user', $params['user'] );
143 $this->addWhere( $actorQuery['conds'] );
144 } elseif ( $params['excludeuser'] !== null ) {
145 $actorQuery = $this->actorMigration->getWhere( $db, 'rev_user', $params['excludeuser'] );
146 $this->addWhere( 'NOT(' . $actorQuery['conds'] . ')' );
147 }
148
149 if ( $params['user'] !== null || $params['excludeuser'] !== null ) {
150 // Paranoia: avoid brute force searches (T19342)
151 if ( !$this->getAuthority()->isAllowed( 'deletedhistory' ) ) {
152 $bitmask = RevisionRecord::DELETED_USER;
153 } elseif ( !$this->getAuthority()->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
154 $bitmask = RevisionRecord::DELETED_USER | RevisionRecord::DELETED_RESTRICTED;
155 } else {
156 $bitmask = 0;
157 }
158 if ( $bitmask ) {
159 $this->addWhere( $db->bitAnd( 'rev_deleted', $bitmask ) . " != $bitmask" );
160 }
161 }
162
163 if ( $params['continue'] !== null ) {
164 $op = ( $dir == 'newer' ? '>=' : '<=' );
165 $cont = $this->parseContinueParamOrDie( $params['continue'], [ 'timestamp', 'int' ] );
166 $this->addWhere( $db->buildComparison( $op, [
167 $tsField => $db->timestamp( $cont[0] ),
168 $idField => $cont[1],
169 ] ) );
170 }
171
172 $this->addOption( 'LIMIT', $this->limit + 1 );
173
174 $sort = ( $dir == 'newer' ? '' : ' DESC' );
175 $orderby = [];
176 // Targeting index rev_timestamp, user_timestamp, usertext_timestamp, or actor_timestamp.
177 // But 'user' is always constant for the latter three, so it doesn't matter here.
178 $orderby[] = "rev_timestamp $sort";
179 $orderby[] = "rev_id $sort";
180 $this->addOption( 'ORDER BY', $orderby );
181
182 $hookData = [];
183 $res = $this->select( __METHOD__, [], $hookData );
184
185 if ( $resultPageSet === null ) {
186 $this->executeGenderCacheFromResultWrapper( $res, __METHOD__ );
187 }
188
189 $pageMap = []; // Maps rev_page to array index
190 $count = 0;
191 $nextIndex = 0;
192 $generated = [];
193 foreach ( $res as $row ) {
194 if ( $count === 0 && $resultPageSet !== null ) {
195 // Set the non-continue since the list of all revisions is
196 // prone to having entries added at the start frequently.
197 $this->getContinuationManager()->addGeneratorNonContinueParam(
198 $this, 'continue', "$row->rev_timestamp|$row->rev_id"
199 );
200 }
201 if ( ++$count > $this->limit ) {
202 // We've had enough
203 $this->setContinueEnumParameter( 'continue', "$row->rev_timestamp|$row->rev_id" );
204 break;
205 }
206
207 // Miser mode namespace check
208 if ( $miser_ns !== null && !in_array( $row->page_namespace, $miser_ns ) ) {
209 continue;
210 }
211
212 if ( $resultPageSet !== null ) {
213 if ( $params['generatetitles'] ) {
214 $generated[$row->rev_page] = $row->rev_page;
215 } else {
216 $generated[] = $row->rev_id;
217 }
218 } else {
219 $revision = $this->revisionStore->newRevisionFromRow( $row, 0, Title::newFromRow( $row ) );
220 $rev = $this->extractRevisionInfo( $revision, $row );
221
222 if ( !isset( $pageMap[$row->rev_page] ) ) {
223 $index = $nextIndex++;
224 $pageMap[$row->rev_page] = $index;
225 $title = Title::newFromPageIdentity( $revision->getPage() );
226 $a = [
227 'pageid' => $title->getArticleID(),
228 'revisions' => [ $rev ],
229 ];
230 ApiResult::setIndexedTagName( $a['revisions'], 'rev' );
231 ApiQueryBase::addTitleInfo( $a, $title );
232 $fit = $this->processRow( $row, $a['revisions'][0], $hookData ) &&
233 $result->addValue( [ 'query', $this->getModuleName() ], $index, $a );
234 } else {
235 $index = $pageMap[$row->rev_page];
236 $fit = $this->processRow( $row, $rev, $hookData ) &&
237 $result->addValue( [ 'query', $this->getModuleName(), $index, 'revisions' ], null, $rev );
238 }
239 if ( !$fit ) {
240 $this->setContinueEnumParameter( 'continue', "$row->rev_timestamp|$row->rev_id" );
241 break;
242 }
243 }
244 }
245
246 if ( $resultPageSet !== null ) {
247 if ( $params['generatetitles'] ) {
248 $resultPageSet->populateFromPageIDs( $generated );
249 } else {
250 $resultPageSet->populateFromRevisionIDs( $generated );
251 }
252 } else {
253 $result->addIndexedTagName( [ 'query', $this->getModuleName() ], 'page' );
254 }
255 }
256
258 public function getAllowedParams() {
259 $ret = parent::getAllowedParams() + [
260 'user' => [
261 ParamValidator::PARAM_TYPE => 'user',
262 UserDef::PARAM_ALLOWED_USER_TYPES => [ 'name', 'ip', 'temp', 'id', 'interwiki' ],
263 UserDef::PARAM_RETURN_OBJECT => true,
264 ],
265 'namespace' => [
266 ParamValidator::PARAM_ISMULTI => true,
267 ParamValidator::PARAM_TYPE => 'namespace',
268 ParamValidator::PARAM_DEFAULT => null,
269 ],
270 'start' => [
271 ParamValidator::PARAM_TYPE => 'timestamp',
272 ],
273 'end' => [
274 ParamValidator::PARAM_TYPE => 'timestamp',
275 ],
276 'dir' => [
277 ParamValidator::PARAM_TYPE => [
278 'newer',
279 'older'
280 ],
281 ParamValidator::PARAM_DEFAULT => 'older',
282 ApiBase::PARAM_HELP_MSG => 'api-help-param-direction',
284 'newer' => 'api-help-paramvalue-direction-newer',
285 'older' => 'api-help-paramvalue-direction-older',
286 ],
287 ],
288 'excludeuser' => [
289 ParamValidator::PARAM_TYPE => 'user',
290 UserDef::PARAM_ALLOWED_USER_TYPES => [ 'name', 'ip', 'temp', 'id', 'interwiki' ],
291 UserDef::PARAM_RETURN_OBJECT => true,
292 ],
293 'continue' => [
294 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
295 ],
296 'generatetitles' => [
297 ParamValidator::PARAM_DEFAULT => false,
298 ],
299 ];
300
301 if ( $this->getConfig()->get( MainConfigNames::MiserMode ) ) {
302 $ret['namespace'][ApiBase::PARAM_HELP_MSG_APPEND] = [
303 'api-help-param-limited-in-miser-mode',
304 ];
305 }
306
307 return $ret;
308 }
309
311 protected function getExamplesMessages() {
312 return [
313 'action=query&list=allrevisions&arvuser=Example&arvlimit=50'
314 => 'apihelp-query+allrevisions-example-user',
315 'action=query&list=allrevisions&arvdir=newer&arvlimit=50'
316 => 'apihelp-query+allrevisions-example-ns-any',
317 ];
318 }
319
321 public function getHelpUrls() {
322 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Allrevisions';
323 }
324}
325
327class_alias( ApiQueryAllRevisions::class, 'ApiQueryAllRevisions' );
getModuleName()
Get the name of the module being executed by this instance.
Definition ApiBase.php:557
parseContinueParamOrDie(string $continue, array $types)
Parse the 'continue' parameter in the usual format and validate the types of each part,...
Definition ApiBase.php:1707
getResult()
Get the result object.
Definition ApiBase.php:696
const PARAM_HELP_MSG_PER_VALUE
((string|array|Message)[]) When PARAM_TYPE is an array, or 'string' with PARAM_ISMULTI,...
Definition ApiBase.php:206
requireMaxOneParameter( $params,... $required)
Dies if more than one parameter from a certain set of parameters are set and not false.
Definition ApiBase.php:1012
const PARAM_HELP_MSG_APPEND
((string|array|Message)[]) Specify additional i18n messages to append to the normal message for this ...
Definition ApiBase.php:174
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition ApiBase.php:166
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition ApiBase.php:837
getParameter( $paramName, $parseLimit=true)
Get a value for the given parameter.
Definition ApiBase.php:958
This class contains a list of pages that the client has requested.
Query module to enumerate all revisions.
run(?ApiPageSet $resultPageSet=null)
getExamplesMessages()
Returns usage examples for this module.Return value has query strings as keys, with values being eith...
__construct(ApiQuery $query, string $moduleName, private readonly RevisionStore $revisionStore, IContentHandlerFactory $contentHandlerFactory, ParserFactory $parserFactory, SlotRoleRegistry $slotRoleRegistry, private readonly ActorMigration $actorMigration, private readonly NamespaceInfo $namespaceInfo, private readonly ChangeTagsStore $changeTagsStore, ContentRenderer $contentRenderer, ContentTransformer $contentTransformer, CommentFormatter $commentFormatter, TempUserCreator $tempUserCreator, UserFactory $userFactory,)
getHelpUrls()
Return links to more detailed help pages about the module.1.25, returning boolean false is deprecated...
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.
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...
processRow( $row, array &$data, array &$hookData)
Call the ApiQueryBaseProcessRow hook.
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:36
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.
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:69
This is not intended to be a long-term part of MediaWiki; it will be deprecated and removed once acto...
Service for temporary user creation.
Create User objects.
Service for formatting and validating API parameters.
addTables( $tables, $alias=null)
addWhere( $conds)
addFields( $fields)