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