MediaWiki  master
ApiQueryAllRevisions.php
Go to the documentation of this file.
1 <?php
26 
34 
39  public function __construct( ApiQuery $query, $moduleName ) {
40  parent::__construct( $query, $moduleName, 'arv' );
41  }
42 
47  protected function run( ApiPageSet $resultPageSet = null ) {
48  $db = $this->getDB();
49  $params = $this->extractRequestParams( false );
50  $services = MediaWikiServices::getInstance();
51  $revisionStore = $services->getRevisionStore();
52 
53  $result = $this->getResult();
54 
55  $this->requireMaxOneParameter( $params, 'user', 'excludeuser' );
56 
57  $tsField = 'rev_timestamp';
58  $idField = 'rev_id';
59  $pageField = 'rev_page';
60  if ( $params['user'] !== null ) {
61  // The query is probably best done using the actor_timestamp index on
62  // revision_actor_temp. Use the denormalized fields from that table.
63  $tsField = 'revactor_timestamp';
64  $idField = 'revactor_rev';
65  $pageField = 'revactor_page';
66  }
67 
68  // Namespace check is likely to be desired, but can't be done
69  // efficiently in SQL.
70  $miser_ns = null;
71  $needPageTable = false;
72  if ( $params['namespace'] !== null ) {
73  $params['namespace'] = array_unique( $params['namespace'] );
74  sort( $params['namespace'] );
75  if ( $params['namespace'] != $services->getNamespaceInfo()->getValidNamespaces() ) {
76  $needPageTable = true;
77  if ( $this->getConfig()->get( 'MiserMode' ) ) {
78  $miser_ns = $params['namespace'];
79  } else {
80  $this->addWhere( [ 'page_namespace' => $params['namespace'] ] );
81  }
82  }
83  }
84 
85  if ( $resultPageSet === null ) {
86  $this->parseParameters( $params );
87  $revQuery = $revisionStore->getQueryInfo( [ 'page' ] );
88  } else {
89  $this->limit = $this->getParameter( 'limit' ) ?: 10;
90  $revQuery = [
91  'tables' => [ 'revision' ],
92  'fields' => [ 'rev_timestamp', 'rev_id' ],
93  'joins' => [],
94  ];
95 
96  if ( $params['generatetitles'] ) {
97  $revQuery['fields'][] = 'rev_page';
98  }
99 
100  if ( $params['user'] !== null || $params['excludeuser'] !== null ) {
101  $actorQuery = ActorMigration::newMigration()->getJoin( 'rev_user' );
102  $revQuery['tables'] += $actorQuery['tables'];
103  $revQuery['joins'] += $actorQuery['joins'];
104  }
105 
106  if ( $needPageTable ) {
107  $revQuery['tables'][] = 'page';
108  $revQuery['joins']['page'] = [ 'JOIN', [ "$pageField = page_id" ] ];
109  if ( (bool)$miser_ns ) {
110  $revQuery['fields'][] = 'page_namespace';
111  }
112  }
113  }
114 
115  // If we're going to be using actor_timestamp, we need to swap the order of `revision`
116  // and `revision_actor_temp` in the query (for the straight join) and adjust some field aliases.
117  if ( $idField !== 'rev_id' && isset( $revQuery['tables']['temp_rev_user'] ) ) {
118  $aliasFields = [ 'rev_id' => $idField, 'rev_timestamp' => $tsField, 'rev_page' => $pageField ];
119  $revQuery['fields'] = array_merge(
120  $aliasFields,
121  array_diff( $revQuery['fields'], array_keys( $aliasFields ) )
122  );
123  unset( $revQuery['tables']['temp_rev_user'] );
124  $revQuery['tables'] = array_merge(
125  [ 'temp_rev_user' => 'revision_actor_temp' ],
126  $revQuery['tables']
127  );
128  $revQuery['joins']['revision'] = $revQuery['joins']['temp_rev_user'];
129  unset( $revQuery['joins']['temp_rev_user'] );
130  }
131 
132  $this->addTables( $revQuery['tables'] );
133  $this->addFields( $revQuery['fields'] );
134  $this->addJoinConds( $revQuery['joins'] );
135 
136  // Seems to be needed to avoid a planner bug (T113901)
137  $this->addOption( 'STRAIGHT_JOIN' );
138 
139  $dir = $params['dir'];
140  $this->addTimestampWhereRange( $tsField, $dir, $params['start'], $params['end'] );
141 
142  if ( $this->fld_tags ) {
143  $this->addFields( [ 'ts_tags' => ChangeTags::makeTagSummarySubquery( 'revision' ) ] );
144  }
145 
146  if ( $params['user'] !== null ) {
147  $actorQuery = ActorMigration::newMigration()
148  ->getWhere( $db, 'rev_user', $params['user'] );
149  $this->addWhere( $actorQuery['conds'] );
150  } elseif ( $params['excludeuser'] !== null ) {
151  $actorQuery = ActorMigration::newMigration()
152  ->getWhere( $db, 'rev_user', $params['excludeuser'] );
153  $this->addWhere( 'NOT(' . $actorQuery['conds'] . ')' );
154  }
155 
156  if ( $params['user'] !== null || $params['excludeuser'] !== null ) {
157  // Paranoia: avoid brute force searches (T19342)
158  if ( !$this->getAuthority()->isAllowed( 'deletedhistory' ) ) {
159  $bitmask = RevisionRecord::DELETED_USER;
160  } elseif ( !$this->getAuthority()->isAllowedAny( 'suppressrevision', 'viewsuppressed' )
161  ) {
162  $bitmask = RevisionRecord::DELETED_USER | RevisionRecord::DELETED_RESTRICTED;
163  } else {
164  $bitmask = 0;
165  }
166  if ( $bitmask ) {
167  $this->addWhere( $db->bitAnd( 'rev_deleted', $bitmask ) . " != $bitmask" );
168  }
169  }
170 
171  if ( $params['continue'] !== null ) {
172  $op = ( $dir == 'newer' ? '>' : '<' );
173  $cont = explode( '|', $params['continue'] );
174  $this->dieContinueUsageIf( count( $cont ) != 2 );
175  $ts = $db->addQuotes( $db->timestamp( $cont[0] ) );
176  $rev_id = (int)$cont[1];
177  $this->dieContinueUsageIf( strval( $rev_id ) !== $cont[1] );
178  $this->addWhere( "$tsField $op $ts OR " .
179  "($tsField = $ts AND " .
180  "$idField $op= $rev_id)" );
181  }
182 
183  $this->addOption( 'LIMIT', $this->limit + 1 );
184 
185  $sort = ( $dir == 'newer' ? '' : ' DESC' );
186  $orderby = [];
187  // Targeting index rev_timestamp, user_timestamp, usertext_timestamp, or actor_timestamp.
188  // But 'user' is always constant for the latter three, so it doesn't matter here.
189  $orderby[] = "rev_timestamp $sort";
190  $orderby[] = "rev_id $sort";
191  $this->addOption( 'ORDER BY', $orderby );
192 
193  $hookData = [];
194  $res = $this->select( __METHOD__, [], $hookData );
195 
196  if ( $resultPageSet === null ) {
197  $this->executeGenderCacheFromResultWrapper( $res, __METHOD__ );
198  }
199 
200  $pageMap = []; // Maps rev_page to array index
201  $count = 0;
202  $nextIndex = 0;
203  $generated = [];
204  foreach ( $res as $row ) {
205  if ( $count === 0 && $resultPageSet !== null ) {
206  // Set the non-continue since the list of all revisions is
207  // prone to having entries added at the start frequently.
208  $this->getContinuationManager()->addGeneratorNonContinueParam(
209  $this, 'continue', "$row->rev_timestamp|$row->rev_id"
210  );
211  }
212  if ( ++$count > $this->limit ) {
213  // We've had enough
214  $this->setContinueEnumParameter( 'continue', "$row->rev_timestamp|$row->rev_id" );
215  break;
216  }
217 
218  // Miser mode namespace check
219  if ( $miser_ns !== null && !in_array( $row->page_namespace, $miser_ns ) ) {
220  continue;
221  }
222 
223  if ( $resultPageSet !== null ) {
224  if ( $params['generatetitles'] ) {
225  $generated[$row->rev_page] = $row->rev_page;
226  } else {
227  $generated[] = $row->rev_id;
228  }
229  } else {
230  $revision = $revisionStore->newRevisionFromRow( $row, 0, Title::newFromRow( $row ) );
231  $rev = $this->extractRevisionInfo( $revision, $row );
232 
233  if ( !isset( $pageMap[$row->rev_page] ) ) {
234  $index = $nextIndex++;
235  $pageMap[$row->rev_page] = $index;
236  $title = Title::newFromLinkTarget( $revision->getPageAsLinkTarget() );
237  $a = [
238  'pageid' => $title->getArticleID(),
239  'revisions' => [ $rev ],
240  ];
241  ApiResult::setIndexedTagName( $a['revisions'], 'rev' );
243  $fit = $this->processRow( $row, $a['revisions'][0], $hookData ) &&
244  $result->addValue( [ 'query', $this->getModuleName() ], $index, $a );
245  } else {
246  $index = $pageMap[$row->rev_page];
247  $fit = $this->processRow( $row, $rev, $hookData ) &&
248  $result->addValue( [ 'query', $this->getModuleName(), $index, 'revisions' ], null, $rev );
249  }
250  if ( !$fit ) {
251  $this->setContinueEnumParameter( 'continue', "$row->rev_timestamp|$row->rev_id" );
252  break;
253  }
254  }
255  }
256 
257  if ( $resultPageSet !== null ) {
258  if ( $params['generatetitles'] ) {
259  $resultPageSet->populateFromPageIDs( $generated );
260  } else {
261  $resultPageSet->populateFromRevisionIDs( $generated );
262  }
263  } else {
264  $result->addIndexedTagName( [ 'query', $this->getModuleName() ], 'page' );
265  }
266  }
267 
268  public function getAllowedParams() {
269  $ret = parent::getAllowedParams() + [
270  'user' => [
271  ApiBase::PARAM_TYPE => 'user',
272  UserDef::PARAM_ALLOWED_USER_TYPES => [ 'name', 'ip', 'id', 'interwiki' ],
273  UserDef::PARAM_RETURN_OBJECT => true,
274  ],
275  'namespace' => [
276  ApiBase::PARAM_ISMULTI => true,
277  ApiBase::PARAM_TYPE => 'namespace',
278  ApiBase::PARAM_DFLT => null,
279  ],
280  'start' => [
281  ApiBase::PARAM_TYPE => 'timestamp',
282  ],
283  'end' => [
284  ApiBase::PARAM_TYPE => 'timestamp',
285  ],
286  'dir' => [
288  'newer',
289  'older'
290  ],
291  ApiBase::PARAM_DFLT => 'older',
292  ApiBase::PARAM_HELP_MSG => 'api-help-param-direction',
293  ],
294  'excludeuser' => [
295  ApiBase::PARAM_TYPE => 'user',
296  UserDef::PARAM_ALLOWED_USER_TYPES => [ 'name', 'ip', 'id', 'interwiki' ],
297  UserDef::PARAM_RETURN_OBJECT => true,
298  ],
299  'continue' => [
300  ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
301  ],
302  'generatetitles' => [
303  ApiBase::PARAM_DFLT => false,
304  ],
305  ];
306 
307  if ( $this->getConfig()->get( 'MiserMode' ) ) {
308  $ret['namespace'][ApiBase::PARAM_HELP_MSG_APPEND] = [
309  'api-help-param-limited-in-miser-mode',
310  ];
311  }
312 
313  return $ret;
314  }
315 
316  protected function getExamplesMessages() {
317  return [
318  'action=query&list=allrevisions&arvuser=Example&arvlimit=50'
319  => 'apihelp-query+allrevisions-example-user',
320  'action=query&list=allrevisions&arvdir=newer&arvlimit=50'
321  => 'apihelp-query+allrevisions-example-ns-any',
322  ];
323  }
324 
325  public function getHelpUrls() {
326  return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Allrevisions';
327  }
328 }
ApiQueryRevisionsBase\parseParameters
parseParameters( $params)
Parse the parameters into the various instance fields.
Definition: ApiQueryRevisionsBase.php:80
ContextSource\getConfig
getConfig()
Definition: ContextSource.php:71
ChangeTags\makeTagSummarySubquery
static makeTagSummarySubquery( $tables)
Make the tag summary subquery based on the given tables and return it.
Definition: ChangeTags.php:950
ApiQueryBase\processRow
processRow( $row, array &$data, array &$hookData)
Call the ApiQueryBaseProcessRow hook.
Definition: ApiQueryBase.php:449
ApiQueryBase\addFields
addFields( $value)
Add a set of fields to select to the internal array.
Definition: ApiQueryBase.php:212
ApiQueryAllRevisions\run
run(ApiPageSet $resultPageSet=null)
Definition: ApiQueryAllRevisions.php:47
ApiQuery
This is the main query class.
Definition: ApiQuery.php:37
Revision\RevisionRecord
Page revision base class.
Definition: RevisionRecord.php:47
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:173
ApiQueryAllRevisions\getExamplesMessages
getExamplesMessages()
Returns usage examples for this module.
Definition: ApiQueryAllRevisions.php:316
ApiQueryBase\addTimestampWhereRange
addTimestampWhereRange( $field, $dir, $start, $end, $sort=true)
Add a WHERE clause corresponding to a range, similar to addWhereRange, but converts $start and $end t...
Definition: ApiQueryBase.php:366
ApiBase\PARAM_HELP_MSG
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition: ApiBase.php:105
ApiBase\PARAM_TYPE
const PARAM_TYPE
Definition: ApiBase.php:72
ApiBase\getResult
getResult()
Get the result object.
Definition: ApiBase.php:561
ApiQueryAllRevisions\getHelpUrls
getHelpUrls()
Return links to more detailed help pages about the module.
Definition: ApiQueryAllRevisions.php:325
ApiQueryBase\addOption
addOption( $name, $value=null)
Add an option such as LIMIT or USE INDEX.
Definition: ApiQueryBase.php:378
$res
$res
Definition: testCompression.php:57
$revQuery
$revQuery
Definition: testCompression.php:56
ApiBase\PARAM_HELP_MSG_APPEND
const PARAM_HELP_MSG_APPEND
((string|array|Message)[]) Specify additional i18n messages to append to the normal message for this ...
Definition: ApiBase.php:112
ActorMigration\newMigration
static newMigration()
Static constructor.
Definition: ActorMigration.php:148
ApiPageSet
This class contains a list of pages that the client has requested.
Definition: ApiPageSet.php:42
Wikimedia\ParamValidator\ParamValidator::TypeDef\UserDef
Type definition for user types.
Definition: UserDef.php:25
ApiQueryRevisionsBase
A base class for functions common to producing a list of revisions.
Definition: ApiQueryRevisionsBase.php:39
ApiQueryGeneratorBase\setContinueEnumParameter
setContinueEnumParameter( $paramName, $paramValue)
Overridden to set the generator param if in generator mode.
Definition: ApiQueryGeneratorBase.php:83
ApiQueryBase\executeGenderCacheFromResultWrapper
executeGenderCacheFromResultWrapper(IResultWrapper $res, $fname=__METHOD__, $fieldPrefix='page')
Preprocess the result set to fill the GenderCache with the necessary information before using self::a...
Definition: ApiQueryBase.php:625
Title\newFromRow
static newFromRow( $row)
Make a Title object from a DB row.
Definition: Title.php:558
ApiQueryAllRevisions\getAllowedParams
getAllowedParams()
Definition: ApiQueryAllRevisions.php:268
ApiQueryBase\getDB
getDB()
Get the Query database connection (read-only)
Definition: ApiQueryBase.php:117
ApiQueryBase\addTables
addTables( $tables, $alias=null)
Add a set of tables to the internal array.
Definition: ApiQueryBase.php:182
ApiQueryBase\select
select( $method, $extraQuery=[], array &$hookData=null)
Execute a SELECT query based on the values in the internal arrays.
Definition: ApiQueryBase.php:399
ApiBase\extractRequestParams
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition: ApiBase.php:720
$title
$title
Definition: testCompression.php:38
ApiQueryAllRevisions
Query module to enumerate all revisions.
Definition: ApiQueryAllRevisions.php:33
ApiBase\getContinuationManager
getContinuationManager()
Definition: ApiBase.php:601
ApiResult\setIndexedTagName
static setIndexedTagName(array &$arr, $tag)
Set the tag name for numeric-keyed values in XML format.
Definition: ApiResult.php:607
ApiBase\requireMaxOneParameter
requireMaxOneParameter( $params,... $required)
Die if more than one of a certain set of parameters is set and not false.
Definition: ApiBase.php:892
ApiBase\dieContinueUsageIf
dieContinueUsageIf( $condition)
Die with the 'badcontinue' error.
Definition: ApiBase.php:1567
ContextSource\getAuthority
getAuthority()
Definition: ContextSource.php:142
ApiQueryRevisionsBase\extractRevisionInfo
extractRevisionInfo(RevisionRecord $revision, $row)
Extract information from the RevisionRecord.
Definition: ApiQueryRevisionsBase.php:236
ApiQueryBase\addJoinConds
addJoinConds( $join_conds)
Add a set of JOIN conditions to the internal array.
Definition: ApiQueryBase.php:201
Title\newFromLinkTarget
static newFromLinkTarget(LinkTarget $linkTarget, $forceClone='')
Returns a Title given a LinkTarget.
Definition: Title.php:291
ApiBase\PARAM_DFLT
const PARAM_DFLT
Definition: ApiBase.php:70
ApiBase\getParameter
getParameter( $paramName, $parseLimit=true)
Get a value for the given parameter.
Definition: ApiBase.php:840
ApiBase\getModuleName
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:440
ApiBase\PARAM_ISMULTI
const PARAM_ISMULTI
Definition: ApiBase.php:71
ApiQueryBase\addWhere
addWhere( $value)
Add a set of WHERE clauses to the internal array.
Definition: ApiQueryBase.php:245
ApiQueryAllRevisions\__construct
__construct(ApiQuery $query, $moduleName)
Definition: ApiQueryAllRevisions.php:39
ApiQueryBase\addTitleInfo
static addTitleInfo(&$arr, $title, $prefix='')
Add information (title and namespace) about a Title object to a result array.
Definition: ApiQueryBase.php:466