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