MediaWiki  1.27.2
ApiQueryRevisions.php
Go to the documentation of this file.
1 <?php
36 
37  private $token = null;
38 
39  public function __construct( ApiQuery $query, $moduleName ) {
40  parent::__construct( $query, $moduleName, 'rv' );
41  }
42 
43  private $tokenFunctions;
44 
46  protected function getTokenFunctions() {
47  // tokenname => function
48  // function prototype is func($pageid, $title, $rev)
49  // should return token or false
50 
51  // Don't call the hooks twice
52  if ( isset( $this->tokenFunctions ) ) {
53  return $this->tokenFunctions;
54  }
55 
56  // If we're in a mode that breaks the same-origin policy, no tokens can
57  // be obtained
58  if ( $this->lacksSameOriginSecurity() ) {
59  return [];
60  }
61 
62  $this->tokenFunctions = [
63  'rollback' => [ 'ApiQueryRevisions', 'getRollbackToken' ]
64  ];
65  Hooks::run( 'APIQueryRevisionsTokens', [ &$this->tokenFunctions ] );
66 
67  return $this->tokenFunctions;
68  }
69 
77  public static function getRollbackToken( $pageid, $title, $rev ) {
79  if ( !$wgUser->isAllowed( 'rollback' ) ) {
80  return false;
81  }
82 
83  return $wgUser->getEditToken(
84  [ $title->getPrefixedText(), $rev->getUserText() ] );
85  }
86 
87  protected function run( ApiPageSet $resultPageSet = null ) {
88  $params = $this->extractRequestParams( false );
89 
90  // If any of those parameters are used, work in 'enumeration' mode.
91  // Enum mode can only be used when exactly one page is provided.
92  // Enumerating revisions on multiple pages make it extremely
93  // difficult to manage continuations and require additional SQL indexes
94  $enumRevMode = ( $params['user'] !== null || $params['excludeuser'] !== null ||
95  $params['limit'] !== null || $params['startid'] !== null ||
96  $params['endid'] !== null || $params['dir'] === 'newer' ||
97  $params['start'] !== null || $params['end'] !== null );
98 
99  $pageSet = $this->getPageSet();
100  $pageCount = $pageSet->getGoodTitleCount();
101  $revCount = $pageSet->getRevisionCount();
102 
103  // Optimization -- nothing to do
104  if ( $revCount === 0 && $pageCount === 0 ) {
105  // Nothing to do
106  return;
107  }
108  if ( $revCount > 0 && count( $pageSet->getLiveRevisionIDs() ) === 0 ) {
109  // We're in revisions mode but all given revisions are deleted
110  return;
111  }
112 
113  if ( $revCount > 0 && $enumRevMode ) {
114  $this->dieUsage(
115  'The revids= parameter may not be used with the list options ' .
116  '(limit, startid, endid, dirNewer, start, end).',
117  'revids'
118  );
119  }
120 
121  if ( $pageCount > 1 && $enumRevMode ) {
122  $this->dieUsage(
123  'titles, pageids or a generator was used to supply multiple pages, ' .
124  'but the limit, startid, endid, dirNewer, user, excludeuser, start ' .
125  'and end parameters may only be used on a single page.',
126  'multpages'
127  );
128  }
129 
130  // In non-enum mode, rvlimit can't be directly used. Use the maximum
131  // allowed value.
132  if ( !$enumRevMode ) {
133  $this->setParsedLimit = false;
134  $params['limit'] = 'max';
135  }
136 
137  $db = $this->getDB();
138  $this->addTables( [ 'revision', 'page' ] );
139  $this->addJoinConds(
140  [ 'page' => [ 'INNER JOIN', [ 'page_id = rev_page' ] ] ]
141  );
142 
143  if ( $resultPageSet === null ) {
144  $this->parseParameters( $params );
145  $this->token = $params['token'];
146  $this->addFields( Revision::selectFields() );
147  if ( $this->token !== null || $pageCount > 0 ) {
149  }
150  } else {
151  $this->limit = $this->getParameter( 'limit' ) ?: 10;
152  $this->addFields( [ 'rev_id', 'rev_timestamp', 'rev_page' ] );
153  }
154 
155  if ( $this->fld_tags ) {
156  $this->addTables( 'tag_summary' );
157  $this->addJoinConds(
158  [ 'tag_summary' => [ 'LEFT JOIN', [ 'rev_id=ts_rev_id' ] ] ]
159  );
160  $this->addFields( 'ts_tags' );
161  }
162 
163  if ( $params['tag'] !== null ) {
164  $this->addTables( 'change_tag' );
165  $this->addJoinConds(
166  [ 'change_tag' => [ 'INNER JOIN', [ 'rev_id=ct_rev_id' ] ] ]
167  );
168  $this->addWhereFld( 'ct_tag', $params['tag'] );
169  }
170 
171  if ( $this->fetchContent ) {
172  // For each page we will request, the user must have read rights for that page
173  $user = $this->getUser();
175  foreach ( $pageSet->getGoodTitles() as $title ) {
176  if ( !$title->userCan( 'read', $user ) ) {
177  $this->dieUsage(
178  'The current user is not allowed to read ' . $title->getPrefixedText(),
179  'accessdenied' );
180  }
181  }
182 
183  $this->addTables( 'text' );
184  $this->addJoinConds(
185  [ 'text' => [ 'INNER JOIN', [ 'rev_text_id=old_id' ] ] ]
186  );
187  $this->addFields( 'old_id' );
189  }
190 
191  // add user name, if needed
192  if ( $this->fld_user ) {
193  $this->addTables( 'user' );
194  $this->addJoinConds( [ 'user' => Revision::userJoinCond() ] );
196  }
197 
198  if ( $enumRevMode ) {
199  // Indexes targeted:
200  // page_timestamp if we don't have rvuser
201  // page_user_timestamp if we have a logged-in rvuser
202  // page_timestamp or usertext_timestamp if we have an IP rvuser
203 
204  // This is mostly to prevent parameter errors (and optimize SQL?)
205  if ( $params['startid'] !== null && $params['start'] !== null ) {
206  $this->dieUsage( 'start and startid cannot be used together', 'badparams' );
207  }
208 
209  if ( $params['endid'] !== null && $params['end'] !== null ) {
210  $this->dieUsage( 'end and endid cannot be used together', 'badparams' );
211  }
212 
213  if ( $params['user'] !== null && $params['excludeuser'] !== null ) {
214  $this->dieUsage( 'user and excludeuser cannot be used together', 'badparams' );
215  }
216 
217  if ( $params['continue'] !== null ) {
218  $cont = explode( '|', $params['continue'] );
219  $this->dieContinueUsageIf( count( $cont ) != 2 );
220  $op = ( $params['dir'] === 'newer' ? '>' : '<' );
221  $continueTimestamp = $db->addQuotes( $db->timestamp( $cont[0] ) );
222  $continueId = (int)$cont[1];
223  $this->dieContinueUsageIf( $continueId != $cont[1] );
224  $this->addWhere( "rev_timestamp $op $continueTimestamp OR " .
225  "(rev_timestamp = $continueTimestamp AND " .
226  "rev_id $op= $continueId)"
227  );
228  }
229 
230  $this->addTimestampWhereRange( 'rev_timestamp', $params['dir'],
231  $params['start'], $params['end'] );
232  $this->addWhereRange( 'rev_id', $params['dir'],
233  $params['startid'], $params['endid'] );
234 
235  // There is only one ID, use it
236  $ids = array_keys( $pageSet->getGoodTitles() );
237  $this->addWhereFld( 'rev_page', reset( $ids ) );
238 
239  if ( $params['user'] !== null ) {
240  $user = User::newFromName( $params['user'] );
241  if ( $user && $user->getId() > 0 ) {
242  $this->addWhereFld( 'rev_user', $user->getId() );
243  } else {
244  $this->addWhereFld( 'rev_user_text', $params['user'] );
245  }
246  } elseif ( $params['excludeuser'] !== null ) {
247  $user = User::newFromName( $params['excludeuser'] );
248  if ( $user && $user->getId() > 0 ) {
249  $this->addWhere( 'rev_user != ' . $user->getId() );
250  } else {
251  $this->addWhere( 'rev_user_text != ' .
252  $db->addQuotes( $params['excludeuser'] ) );
253  }
254  }
255  if ( $params['user'] !== null || $params['excludeuser'] !== null ) {
256  // Paranoia: avoid brute force searches (bug 17342)
257  if ( !$this->getUser()->isAllowed( 'deletedhistory' ) ) {
258  $bitmask = Revision::DELETED_USER;
259  } elseif ( !$this->getUser()->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
261  } else {
262  $bitmask = 0;
263  }
264  if ( $bitmask ) {
265  $this->addWhere( $db->bitAnd( 'rev_deleted', $bitmask ) . " != $bitmask" );
266  }
267  }
268  } elseif ( $revCount > 0 ) {
269  // Always targets the PRIMARY index
270 
271  $revs = $pageSet->getLiveRevisionIDs();
272 
273  // Get all revision IDs
274  $this->addWhereFld( 'rev_id', array_keys( $revs ) );
275 
276  if ( $params['continue'] !== null ) {
277  $this->addWhere( 'rev_id >= ' . intval( $params['continue'] ) );
278  }
279  $this->addOption( 'ORDER BY', 'rev_id' );
280  } elseif ( $pageCount > 0 ) {
281  // Always targets the rev_page_id index
282 
283  $titles = $pageSet->getGoodTitles();
284 
285  // When working in multi-page non-enumeration mode,
286  // limit to the latest revision only
287  $this->addWhere( 'page_latest=rev_id' );
288 
289  // Get all page IDs
290  $this->addWhereFld( 'page_id', array_keys( $titles ) );
291  // Every time someone relies on equality propagation, god kills a kitten :)
292  $this->addWhereFld( 'rev_page', array_keys( $titles ) );
293 
294  if ( $params['continue'] !== null ) {
295  $cont = explode( '|', $params['continue'] );
296  $this->dieContinueUsageIf( count( $cont ) != 2 );
297  $pageid = intval( $cont[0] );
298  $revid = intval( $cont[1] );
299  $this->addWhere(
300  "rev_page > $pageid OR " .
301  "(rev_page = $pageid AND " .
302  "rev_id >= $revid)"
303  );
304  }
305  $this->addOption( 'ORDER BY', [
306  'rev_page',
307  'rev_id'
308  ] );
309  } else {
310  ApiBase::dieDebug( __METHOD__, 'param validation?' );
311  }
312 
313  $this->addOption( 'LIMIT', $this->limit + 1 );
314 
315  $count = 0;
316  $generated = [];
317  $res = $this->select( __METHOD__ );
318 
319  foreach ( $res as $row ) {
320  if ( ++$count > $this->limit ) {
321  // We've reached the one extra which shows that there are
322  // additional pages to be had. Stop here...
323  if ( $enumRevMode ) {
324  $this->setContinueEnumParameter( 'continue',
325  $row->rev_timestamp . '|' . intval( $row->rev_id ) );
326  } elseif ( $revCount > 0 ) {
327  $this->setContinueEnumParameter( 'continue', intval( $row->rev_id ) );
328  } else {
329  $this->setContinueEnumParameter( 'continue', intval( $row->rev_page ) .
330  '|' . intval( $row->rev_id ) );
331  }
332  break;
333  }
334 
335  if ( $resultPageSet !== null ) {
336  $generated[] = $row->rev_id;
337  } else {
338  $revision = new Revision( $row );
339  $rev = $this->extractRevisionInfo( $revision, $row );
340 
341  if ( $this->token !== null ) {
342  $title = $revision->getTitle();
344  foreach ( $this->token as $t ) {
345  $val = call_user_func( $tokenFunctions[$t], $title->getArticleID(), $title, $revision );
346  if ( $val === false ) {
347  $this->setWarning( "Action '$t' is not allowed for the current user" );
348  } else {
349  $rev[$t . 'token'] = $val;
350  }
351  }
352  }
353 
354  $fit = $this->addPageSubItem( $row->rev_page, $rev, 'rev' );
355  if ( !$fit ) {
356  if ( $enumRevMode ) {
357  $this->setContinueEnumParameter( 'continue',
358  $row->rev_timestamp . '|' . intval( $row->rev_id ) );
359  } elseif ( $revCount > 0 ) {
360  $this->setContinueEnumParameter( 'continue', intval( $row->rev_id ) );
361  } else {
362  $this->setContinueEnumParameter( 'continue', intval( $row->rev_page ) .
363  '|' . intval( $row->rev_id ) );
364  }
365  break;
366  }
367  }
368  }
369 
370  if ( $resultPageSet !== null ) {
371  $resultPageSet->populateFromRevisionIDs( $generated );
372  }
373  }
374 
375  public function getCacheMode( $params ) {
376  if ( isset( $params['token'] ) ) {
377  return 'private';
378  }
379  return parent::getCacheMode( $params );
380  }
381 
382  public function getAllowedParams() {
383  $ret = parent::getAllowedParams() + [
384  'startid' => [
385  ApiBase::PARAM_TYPE => 'integer',
386  ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
387  ],
388  'endid' => [
389  ApiBase::PARAM_TYPE => 'integer',
390  ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
391  ],
392  'start' => [
393  ApiBase::PARAM_TYPE => 'timestamp',
394  ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
395  ],
396  'end' => [
397  ApiBase::PARAM_TYPE => 'timestamp',
398  ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
399  ],
400  'dir' => [
401  ApiBase::PARAM_DFLT => 'older',
403  'newer',
404  'older'
405  ],
406  ApiBase::PARAM_HELP_MSG => 'api-help-param-direction',
407  ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
408  ],
409  'user' => [
410  ApiBase::PARAM_TYPE => 'user',
411  ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
412  ],
413  'excludeuser' => [
414  ApiBase::PARAM_TYPE => 'user',
415  ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
416  ],
417  'tag' => null,
418  'token' => [
420  ApiBase::PARAM_TYPE => array_keys( $this->getTokenFunctions() ),
422  ],
423  'continue' => [
424  ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
425  ],
426  ];
427 
428  $ret['limit'][ApiBase::PARAM_HELP_MSG_INFO] = [ [ 'singlepageonly' ] ];
429 
430  return $ret;
431  }
432 
433  protected function getExamplesMessages() {
434  return [
435  'action=query&prop=revisions&titles=API|Main%20Page&' .
436  'rvprop=timestamp|user|comment|content'
437  => 'apihelp-query+revisions-example-content',
438  'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
439  'rvprop=timestamp|user|comment'
440  => 'apihelp-query+revisions-example-last5',
441  'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
442  'rvprop=timestamp|user|comment&rvdir=newer'
443  => 'apihelp-query+revisions-example-first5',
444  'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
445  'rvprop=timestamp|user|comment&rvdir=newer&rvstart=2006-05-01T00:00:00Z'
446  => 'apihelp-query+revisions-example-first5-after',
447  'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
448  'rvprop=timestamp|user|comment&rvexcludeuser=127.0.0.1'
449  => 'apihelp-query+revisions-example-first5-not-localhost',
450  'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
451  'rvprop=timestamp|user|comment&rvuser=MediaWiki%20default'
452  => 'apihelp-query+revisions-example-first5-user',
453  ];
454  }
455 
456  public function getHelpUrls() {
457  return 'https://www.mediawiki.org/wiki/API:Revisions';
458  }
459 }
static newFromName($name, $validate= 'valid')
Static factory method for creation from username.
Definition: User.php:568
select($method, $extraQuery=[])
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:88
getDB()
Get the Query database connection (read-only)
static getRollbackToken($pageid, $title, $rev)
null for the local wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify $query
Definition: hooks.txt:1418
getParameter($paramName, $parseLimit=true)
Get a value for the given parameter.
Definition: ApiBase.php:709
addWhereFld($field, $value)
Equivalent to addWhere(array($field => $value))
This class contains a list of pages that the client has requested.
Definition: ApiPageSet.php:41
addPageSubItem($pageId, $item, $elemname=null)
Same as addPageSubItems(), but one element of $data at a time.
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition: hooks.txt:1798
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition: ApiBase.php:50
addWhereRange($field, $dir, $start, $end, $sort=true)
Add a WHERE clause corresponding to a range, and an ORDER BY clause to sort in the right direction...
const PARAM_HELP_MSG_INFO
(array) Specify additional information tags for the parameter.
Definition: ApiBase.php:142
lacksSameOriginSecurity()
Returns true if the current request breaks the same-origin policy.
Definition: ApiBase.php:512
extractRequestParams($parseLimit=true)
Using getAllowedParams(), this function makes an array of the values provided by the user...
Definition: ApiBase.php:685
A base class for functions common to producing a list of revisions.
addTimestampWhereRange($field, $dir, $start, $end, $sort=true)
Add a WHERE clause corresponding to a range, similar to addWhereRange, but converts $start and $end t...
setContinueEnumParameter($paramName, $paramValue)
Overridden to set the generator param if in generator mode.
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
addWhere($value)
Add a set of WHERE clauses to the internal array.
extractRevisionInfo(Revision $revision, $row)
Extract information from the Revision.
addJoinConds($join_conds)
Add a set of JOIN conditions to the internal array.
parseParameters($params)
Parse the parameters into the various instance fields.
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
Definition: hooks.txt:1798
run(ApiPageSet $resultPageSet=null)
$res
Definition: database.txt:21
addOption($name, $value=null)
Add an option such as LIMIT or USE INDEX.
$params
static selectFields()
Return the list of revision fields that should be selected to create a new revision.
Definition: Revision.php:429
static selectTextFields()
Return the list of text fields that should be selected to read the revision text. ...
Definition: Revision.php:491
const DELETED_RESTRICTED
Definition: Revision.php:79
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:912
static run($event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:131
This is the main query class.
Definition: ApiQuery.php:38
presenting them properly to the user as errors is done by the caller return true use this to change the list i e etc $rev
Definition: hooks.txt:1584
setWarning($warning)
Set warning section for this module.
Definition: ApiBase.php:1495
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
dieContinueUsageIf($condition)
Die with the $prefix.
Definition: ApiBase.php:2181
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter...
Definition: ApiBase.php:125
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
Definition: hooks.txt:242
A query action to enumerate revisions of a given page, or show top revisions of multiple pages...
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
const DELETED_USER
Definition: Revision.php:78
linkcache txt The LinkCache class maintains a list of article titles and the information about whether or not the article exists in the database This is used to mark up links when displaying a page If the same link appears more than once on any page then it only has to be looked up once In most cases link lookups are done in batches with the LinkBatch class or the equivalent in so the link cache is mostly useful for short snippets of parsed and for links in the navigation areas of the skin The link cache was formerly used to track links used in a document for the purposes of updating the link tables This application is now deprecated To create a you can use the following $titles
Definition: linkcache.txt:17
addFields($value)
Add a set of fields to select to the internal array.
const PARAM_ISMULTI
(boolean) Accept multiple pipe-separated values for this parameter (e.g.
Definition: ApiBase.php:53
dieUsage($description, $errorCode, $httpRespCode=0, $extradata=null)
Throw a UsageException, which will (if uncaught) call the main module's error handler and die with an...
Definition: ApiBase.php:1526
$count
const PARAM_DEPRECATED
(boolean) Is the parameter deprecated (will show a warning)?
Definition: ApiBase.php:106
static selectPageFields()
Return the list of page fields that should be selected from page table.
Definition: Revision.php:502
static dieDebug($method, $message)
Internal code errors should be reported with this method.
Definition: ApiBase.php:2230
__construct(ApiQuery $query, $moduleName)
static userJoinCond()
Return the value of a select() JOIN conds array for the user table.
Definition: Revision.php:410
static selectUserFields()
Return the list of user fields that should be selected from user table.
Definition: Revision.php:517
getUser()
Get the User object.
getPageSet()
Get the PageSet object to work on.
addTables($tables, $alias=null)
Add a set of tables to the internal array.
$wgUser
Definition: Setup.php:794