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