MediaWiki  master
ApiQueryWatchlist.php
Go to the documentation of this file.
1 <?php
25 
33 
35  private $commentStore;
36 
37  public function __construct( ApiQuery $query, $moduleName ) {
38  parent::__construct( $query, $moduleName, 'wl' );
39  }
40 
41  public function execute() {
42  $this->run();
43  }
44 
45  public function executeGenerator( $resultPageSet ) {
46  $this->run( $resultPageSet );
47  }
48 
49  private $fld_ids = false, $fld_title = false, $fld_patrol = false,
50  $fld_flags = false, $fld_timestamp = false, $fld_user = false,
51  $fld_comment = false, $fld_parsedcomment = false, $fld_sizes = false,
54 
59  private function run( $resultPageSet = null ) {
60  $this->selectNamedDB( 'watchlist', DB_REPLICA, 'watchlist' );
61 
62  $params = $this->extractRequestParams();
63 
64  $user = $this->getUser();
65  $wlowner = $this->getWatchlistUser( $params );
66 
67  if ( !is_null( $params['prop'] ) && is_null( $resultPageSet ) ) {
68  $prop = array_flip( $params['prop'] );
69 
70  $this->fld_ids = isset( $prop['ids'] );
71  $this->fld_title = isset( $prop['title'] );
72  $this->fld_flags = isset( $prop['flags'] );
73  $this->fld_user = isset( $prop['user'] );
74  $this->fld_userid = isset( $prop['userid'] );
75  $this->fld_comment = isset( $prop['comment'] );
76  $this->fld_parsedcomment = isset( $prop['parsedcomment'] );
77  $this->fld_timestamp = isset( $prop['timestamp'] );
78  $this->fld_sizes = isset( $prop['sizes'] );
79  $this->fld_patrol = isset( $prop['patrol'] );
80  $this->fld_notificationtimestamp = isset( $prop['notificationtimestamp'] );
81  $this->fld_loginfo = isset( $prop['loginfo'] );
82  $this->fld_tags = isset( $prop['tags'] );
83 
84  if ( $this->fld_patrol && !$user->useRCPatrol() && !$user->useNPPatrol() ) {
85  $this->dieWithError( 'apierror-permissiondenied-patrolflag', 'patrol' );
86  }
87 
88  if ( $this->fld_comment || $this->fld_parsedcomment ) {
89  $this->commentStore = CommentStore::getStore();
90  }
91  }
92 
93  $options = [
94  'dir' => $params['dir'] === 'older'
97  ];
98 
99  if ( is_null( $resultPageSet ) ) {
100  $options['includeFields'] = $this->getFieldsToInclude();
101  } else {
102  $options['usedInGenerator'] = true;
103  }
104 
105  if ( $params['start'] ) {
106  $options['start'] = $params['start'];
107  }
108  if ( $params['end'] ) {
109  $options['end'] = $params['end'];
110  }
111 
112  $startFrom = null;
113  if ( !is_null( $params['continue'] ) ) {
114  $cont = explode( '|', $params['continue'] );
115  $this->dieContinueUsageIf( count( $cont ) != 2 );
116  $continueTimestamp = $cont[0];
117  $continueId = (int)$cont[1];
118  $this->dieContinueUsageIf( $continueId != $cont[1] );
119  $startFrom = [ $continueTimestamp, $continueId ];
120  }
121 
122  if ( $wlowner !== $user ) {
123  $options['watchlistOwner'] = $wlowner;
124  $options['watchlistOwnerToken'] = $params['token'];
125  }
126 
127  if ( !is_null( $params['namespace'] ) ) {
128  $options['namespaceIds'] = $params['namespace'];
129  }
130 
131  if ( $params['allrev'] ) {
132  $options['allRevisions'] = true;
133  }
134 
135  if ( !is_null( $params['show'] ) ) {
136  $show = array_flip( $params['show'] );
137 
138  /* Check for conflicting parameters. */
139  if ( $this->showParamsConflicting( $show ) ) {
140  $this->dieWithError( 'apierror-show' );
141  }
142 
143  // Check permissions.
144  if ( isset( $show[WatchedItemQueryService::FILTER_PATROLLED] )
146  ) {
147  if ( !$user->useRCPatrol() && !$user->useNPPatrol() ) {
148  $this->dieWithError( 'apierror-permissiondenied-patrolflag', 'permissiondenied' );
149  }
150  }
151 
152  $options['filters'] = array_keys( $show );
153  }
154 
155  if ( !is_null( $params['type'] ) ) {
156  try {
157  $rcTypes = RecentChange::parseToRCType( $params['type'] );
158  if ( $rcTypes ) {
159  $options['rcTypes'] = $rcTypes;
160  }
161  } catch ( Exception $e ) {
162  ApiBase::dieDebug( __METHOD__, $e->getMessage() );
163  }
164  }
165 
166  $this->requireMaxOneParameter( $params, 'user', 'excludeuser' );
167  if ( !is_null( $params['user'] ) ) {
168  $options['onlyByUser'] = $params['user'];
169  }
170  if ( !is_null( $params['excludeuser'] ) ) {
171  $options['notByUser'] = $params['excludeuser'];
172  }
173 
174  $options['limit'] = $params['limit'];
175 
176  Hooks::run( 'ApiQueryWatchlistPrepareWatchedItemQueryServiceOptions', [
177  $this, $params, &$options
178  ] );
179 
180  $ids = [];
181  $services = MediaWikiServices::getInstance();
182  $watchedItemQuery = $services->getWatchedItemQueryService();
183  $items = $watchedItemQuery->getWatchedItemsWithRecentChangeInfo( $wlowner, $options, $startFrom );
184 
185  // Get gender information
186  if ( $items !== [] && $resultPageSet === null && $this->fld_title &&
187  $services->getContentLanguage()->needsGenderDistinction()
188  ) {
189  $nsInfo = $services->getNamespaceInfo();
190  $usernames = [];
191  foreach ( $items as list( $watchedItem, $recentChangeInfo ) ) {
192  $linkTarget = $watchedItem->getLinkTarget();
193  if ( $nsInfo->hasGenderDistinction( $linkTarget->getNamespace() ) ) {
194  $usernames[] = $linkTarget->getText();
195  }
196  }
197  if ( $usernames !== [] ) {
198  $services->getGenderCache()->doQuery( $usernames, __METHOD__ );
199  }
200  }
201 
202  foreach ( $items as list( $watchedItem, $recentChangeInfo ) ) {
204  if ( is_null( $resultPageSet ) ) {
205  $vals = $this->extractOutputData( $watchedItem, $recentChangeInfo );
206  $fit = $this->getResult()->addValue( [ 'query', $this->getModuleName() ], null, $vals );
207  if ( !$fit ) {
208  $startFrom = [ $recentChangeInfo['rc_timestamp'], $recentChangeInfo['rc_id'] ];
209  break;
210  }
211  } elseif ( $params['allrev'] ) {
212  $ids[] = (int)$recentChangeInfo['rc_this_oldid'];
213  } else {
214  $ids[] = (int)$recentChangeInfo['rc_cur_id'];
215  }
216  }
217 
218  if ( $startFrom !== null ) {
219  $this->setContinueEnumParameter( 'continue', implode( '|', $startFrom ) );
220  }
221 
222  if ( is_null( $resultPageSet ) ) {
223  $this->getResult()->addIndexedTagName(
224  [ 'query', $this->getModuleName() ],
225  'item'
226  );
227  } elseif ( $params['allrev'] ) {
228  $resultPageSet->populateFromRevisionIDs( $ids );
229  } else {
230  $resultPageSet->populateFromPageIDs( $ids );
231  }
232  }
233 
234  private function getFieldsToInclude() {
235  $includeFields = [];
236  if ( $this->fld_flags ) {
237  $includeFields[] = WatchedItemQueryService::INCLUDE_FLAGS;
238  }
239  if ( $this->fld_user || $this->fld_userid ) {
240  $includeFields[] = WatchedItemQueryService::INCLUDE_USER_ID;
241  }
242  if ( $this->fld_user ) {
243  $includeFields[] = WatchedItemQueryService::INCLUDE_USER;
244  }
245  if ( $this->fld_comment || $this->fld_parsedcomment ) {
246  $includeFields[] = WatchedItemQueryService::INCLUDE_COMMENT;
247  }
248  if ( $this->fld_patrol ) {
251  }
252  if ( $this->fld_sizes ) {
253  $includeFields[] = WatchedItemQueryService::INCLUDE_SIZES;
254  }
255  if ( $this->fld_loginfo ) {
257  }
258  if ( $this->fld_tags ) {
259  $includeFields[] = WatchedItemQueryService::INCLUDE_TAGS;
260  }
261  return $includeFields;
262  }
263 
264  private function showParamsConflicting( array $show ) {
265  return ( isset( $show[WatchedItemQueryService::FILTER_MINOR] )
266  && isset( $show[WatchedItemQueryService::FILTER_NOT_MINOR] ) )
267  || ( isset( $show[WatchedItemQueryService::FILTER_BOT] )
268  && isset( $show[WatchedItemQueryService::FILTER_NOT_BOT] ) )
269  || ( isset( $show[WatchedItemQueryService::FILTER_ANON] )
270  && isset( $show[WatchedItemQueryService::FILTER_NOT_ANON] ) )
271  || ( isset( $show[WatchedItemQueryService::FILTER_PATROLLED] )
275  || ( isset( $show[WatchedItemQueryService::FILTER_AUTOPATROLLED] )
276  && isset( $show[WatchedItemQueryService::FILTER_NOT_PATROLLED] ) )
277  || ( isset( $show[WatchedItemQueryService::FILTER_UNREAD] )
278  && isset( $show[WatchedItemQueryService::FILTER_NOT_UNREAD] ) );
279  }
280 
281  private function extractOutputData( WatchedItem $watchedItem, array $recentChangeInfo ) {
282  /* Determine the title of the page that has been changed. */
283  $title = Title::newFromLinkTarget( $watchedItem->getLinkTarget() );
284  $user = $this->getUser();
285 
286  /* Our output data. */
287  $vals = [];
288  $type = (int)$recentChangeInfo['rc_type'];
289  $vals['type'] = RecentChange::parseFromRCType( $type );
290  $anyHidden = false;
291 
292  /* Create a new entry in the result for the title. */
293  if ( $this->fld_title || $this->fld_ids ) {
294  // These should already have been filtered out of the query, but just in case.
295  if ( $type === RC_LOG && ( $recentChangeInfo['rc_deleted'] & LogPage::DELETED_ACTION ) ) {
296  $vals['actionhidden'] = true;
297  $anyHidden = true;
298  }
299  if ( $type !== RC_LOG ||
301  $recentChangeInfo['rc_deleted'],
302  LogPage::DELETED_ACTION,
303  $user
304  )
305  ) {
306  if ( $this->fld_title ) {
308  }
309  if ( $this->fld_ids ) {
310  $vals['pageid'] = (int)$recentChangeInfo['rc_cur_id'];
311  $vals['revid'] = (int)$recentChangeInfo['rc_this_oldid'];
312  $vals['old_revid'] = (int)$recentChangeInfo['rc_last_oldid'];
313  }
314  }
315  }
316 
317  /* Add user data and 'anon' flag, if user is anonymous. */
318  if ( $this->fld_user || $this->fld_userid ) {
319  if ( $recentChangeInfo['rc_deleted'] & RevisionRecord::DELETED_USER ) {
320  $vals['userhidden'] = true;
321  $anyHidden = true;
322  }
323  if ( RevisionRecord::userCanBitfield(
324  $recentChangeInfo['rc_deleted'],
325  RevisionRecord::DELETED_USER,
326  $user
327  ) ) {
328  if ( $this->fld_userid ) {
329  $vals['userid'] = (int)$recentChangeInfo['rc_user'];
330  // for backwards compatibility
331  $vals['user'] = (int)$recentChangeInfo['rc_user'];
332  }
333 
334  if ( $this->fld_user ) {
335  $vals['user'] = $recentChangeInfo['rc_user_text'];
336  }
337 
338  if ( !$recentChangeInfo['rc_user'] ) {
339  $vals['anon'] = true;
340  }
341  }
342  }
343 
344  /* Add flags, such as new, minor, bot. */
345  if ( $this->fld_flags ) {
346  $vals['bot'] = (bool)$recentChangeInfo['rc_bot'];
347  $vals['new'] = $recentChangeInfo['rc_type'] == RC_NEW;
348  $vals['minor'] = (bool)$recentChangeInfo['rc_minor'];
349  }
350 
351  /* Add sizes of each revision. (Only available on 1.10+) */
352  if ( $this->fld_sizes ) {
353  $vals['oldlen'] = (int)$recentChangeInfo['rc_old_len'];
354  $vals['newlen'] = (int)$recentChangeInfo['rc_new_len'];
355  }
356 
357  /* Add the timestamp. */
358  if ( $this->fld_timestamp ) {
359  $vals['timestamp'] = wfTimestamp( TS_ISO_8601, $recentChangeInfo['rc_timestamp'] );
360  }
361 
362  if ( $this->fld_notificationtimestamp ) {
363  $vals['notificationtimestamp'] = ( $watchedItem->getNotificationTimestamp() == null )
364  ? ''
365  : wfTimestamp( TS_ISO_8601, $watchedItem->getNotificationTimestamp() );
366  }
367 
368  /* Add edit summary / log summary. */
369  if ( $this->fld_comment || $this->fld_parsedcomment ) {
370  if ( $recentChangeInfo['rc_deleted'] & RevisionRecord::DELETED_COMMENT ) {
371  $vals['commenthidden'] = true;
372  $anyHidden = true;
373  }
374  if ( RevisionRecord::userCanBitfield(
375  $recentChangeInfo['rc_deleted'],
376  RevisionRecord::DELETED_COMMENT,
377  $user
378  ) ) {
379  $comment = $this->commentStore->getComment( 'rc_comment', $recentChangeInfo )->text;
380  if ( $this->fld_comment ) {
381  $vals['comment'] = $comment;
382  }
383 
384  if ( $this->fld_parsedcomment ) {
385  $vals['parsedcomment'] = Linker::formatComment( $comment, $title );
386  }
387  }
388  }
389 
390  /* Add the patrolled flag */
391  if ( $this->fld_patrol ) {
392  $vals['patrolled'] = $recentChangeInfo['rc_patrolled'] != RecentChange::PRC_UNPATROLLED;
393  $vals['unpatrolled'] = ChangesList::isUnpatrolled( (object)$recentChangeInfo, $user );
394  $vals['autopatrolled'] = $recentChangeInfo['rc_patrolled'] == RecentChange::PRC_AUTOPATROLLED;
395  }
396 
397  if ( $this->fld_loginfo && $recentChangeInfo['rc_type'] == RC_LOG ) {
398  if ( $recentChangeInfo['rc_deleted'] & LogPage::DELETED_ACTION ) {
399  $vals['actionhidden'] = true;
400  $anyHidden = true;
401  }
403  $recentChangeInfo['rc_deleted'],
404  LogPage::DELETED_ACTION,
405  $user
406  ) ) {
407  $vals['logid'] = (int)$recentChangeInfo['rc_logid'];
408  $vals['logtype'] = $recentChangeInfo['rc_log_type'];
409  $vals['logaction'] = $recentChangeInfo['rc_log_action'];
410  $vals['logparams'] = LogFormatter::newFromRow( $recentChangeInfo )->formatParametersForApi();
411  }
412  }
413 
414  if ( $this->fld_tags ) {
415  if ( $recentChangeInfo['rc_tags'] ) {
416  $tags = explode( ',', $recentChangeInfo['rc_tags'] );
417  ApiResult::setIndexedTagName( $tags, 'tag' );
418  $vals['tags'] = $tags;
419  } else {
420  $vals['tags'] = [];
421  }
422  }
423 
424  if ( $anyHidden && ( $recentChangeInfo['rc_deleted'] & RevisionRecord::DELETED_RESTRICTED ) ) {
425  $vals['suppressed'] = true;
426  }
427 
428  Hooks::run( 'ApiQueryWatchlistExtractOutputData', [
429  $this, $watchedItem, $recentChangeInfo, &$vals
430  ] );
431 
432  return $vals;
433  }
434 
435  public function getAllowedParams() {
436  return [
437  'allrev' => false,
438  'start' => [
439  ApiBase::PARAM_TYPE => 'timestamp'
440  ],
441  'end' => [
442  ApiBase::PARAM_TYPE => 'timestamp'
443  ],
444  'namespace' => [
445  ApiBase::PARAM_ISMULTI => true,
446  ApiBase::PARAM_TYPE => 'namespace'
447  ],
448  'user' => [
449  ApiBase::PARAM_TYPE => 'user',
450  ],
451  'excludeuser' => [
452  ApiBase::PARAM_TYPE => 'user',
453  ],
454  'dir' => [
455  ApiBase::PARAM_DFLT => 'older',
457  'newer',
458  'older'
459  ],
460  ApiHelp::PARAM_HELP_MSG => 'api-help-param-direction',
461  ],
462  'limit' => [
463  ApiBase::PARAM_DFLT => 10,
464  ApiBase::PARAM_TYPE => 'limit',
465  ApiBase::PARAM_MIN => 1,
468  ],
469  'prop' => [
470  ApiBase::PARAM_ISMULTI => true,
471  ApiBase::PARAM_DFLT => 'ids|title|flags',
474  'ids',
475  'title',
476  'flags',
477  'user',
478  'userid',
479  'comment',
480  'parsedcomment',
481  'timestamp',
482  'patrol',
483  'sizes',
484  'notificationtimestamp',
485  'loginfo',
486  'tags',
487  ]
488  ],
489  'show' => [
490  ApiBase::PARAM_ISMULTI => true,
504  ]
505  ],
506  'type' => [
507  ApiBase::PARAM_DFLT => 'edit|new|log|categorize',
508  ApiBase::PARAM_ISMULTI => true,
511  ],
512  'owner' => [
513  ApiBase::PARAM_TYPE => 'user'
514  ],
515  'token' => [
516  ApiBase::PARAM_TYPE => 'string',
517  ApiBase::PARAM_SENSITIVE => true,
518  ],
519  'continue' => [
520  ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
521  ],
522  ];
523  }
524 
525  protected function getExamplesMessages() {
526  return [
527  'action=query&list=watchlist'
528  => 'apihelp-query+watchlist-example-simple',
529  'action=query&list=watchlist&wlprop=ids|title|timestamp|user|comment'
530  => 'apihelp-query+watchlist-example-props',
531  'action=query&list=watchlist&wlallrev=&wlprop=ids|title|timestamp|user|comment'
532  => 'apihelp-query+watchlist-example-allrev',
533  'action=query&generator=watchlist&prop=info'
534  => 'apihelp-query+watchlist-example-generator',
535  'action=query&generator=watchlist&gwlallrev=&prop=revisions&rvprop=timestamp|user'
536  => 'apihelp-query+watchlist-example-generator-rev',
537  'action=query&list=watchlist&wlowner=Example&wltoken=123ABC'
538  => 'apihelp-query+watchlist-example-wlowner',
539  ];
540  }
541 
542  public function getHelpUrls() {
543  return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Watchlist';
544  }
545 }
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below...
Definition: ApiBase.php:94
__construct(ApiQuery $query, $moduleName)
const LIMIT_BIG2
Fast query, apihighlimits limit.
Definition: ApiBase.php:261
getNotificationTimestamp()
Get the notification timestamp of this entry.
Definition: WatchedItem.php:91
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
static getChangeTypes()
Get an array of all change types.
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition: ApiBase.php:55
const LIMIT_BIG1
Fast query, standard limit.
Definition: ApiBase.php:259
const PARAM_MAX
(integer) Max value allowed for the parameter, for PARAM_TYPE &#39;integer&#39; and &#39;limit&#39;.
Definition: ApiBase.php:97
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition: ApiBase.php:2006
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user...
Definition: ApiBase.php:761
const PARAM_HELP_MSG_PER_VALUE
((string|array|Message)[]) When PARAM_TYPE is an array, this is an array mapping those values to $msg...
Definition: ApiBase.php:164
setContinueEnumParameter( $paramName, $paramValue)
Overridden to set the generator param if in generator mode.
static setIndexedTagName(array &$arr, $tag)
Set the tag name for numeric-keyed values in XML format.
Definition: ApiResult.php:616
static parseFromRCType( $rcType)
Parsing RC_* constants to human-readable test.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
static formatComment( $comment, $title=null, $local=false, $wikiId=null)
This function is called by all recent changes variants, by the page history, and by the user contribu...
Definition: Linker.php:1165
showParamsConflicting(array $show)
dieContinueUsageIf( $condition)
Die with the &#39;badcontinue&#39; error.
Definition: ApiBase.php:2200
static userCanBitfield( $bitfield, $field, User $user=null)
Determine if the current user is allowed to view a particular field of this log row, if it&#39;s marked as deleted.
Representation of a pair of user and title for watchlist entries.
Definition: WatchedItem.php:33
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:520
executeGenerator( $resultPageSet)
static newFromRow( $row)
Handy shortcut for constructing a formatter directly from database row.
const PARAM_MAX2
(integer) Max value allowed for the parameter for users with the apihighlimits right, for PARAM_TYPE &#39;limit&#39;.
Definition: ApiBase.php:103
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
selectNamedDB( $name, $db, $groups)
Selects the query database connection with the given name.
This query action allows clients to retrieve a list of recently modified pages that are part of the l...
const PRC_UNPATROLLED
static newFromLinkTarget(LinkTarget $linkTarget, $forceClone='')
Returns a Title given a LinkTarget.
Definition: Title.php:269
const PARAM_SENSITIVE
(boolean) Is the parameter sensitive? Note &#39;password&#39;-type fields are always sensitive regardless of ...
Definition: ApiBase.php:200
getWatchlistUser( $params)
Gets the user for whom to get the watchlist.
Definition: ApiBase.php:1757
static getStore()
static isUnpatrolled( $rc, User $user)
CommentStore $commentStore
extractOutputData(WatchedItem $watchedItem, array $recentChangeInfo)
const PARAM_ISMULTI
(boolean) Accept multiple pipe-separated values for this parameter (e.g.
Definition: ApiBase.php:58
static parseToRCType( $type)
Parsing text to RC_* constants.
static dieDebug( $method, $message)
Internal code errors should be reported with this method.
Definition: ApiBase.php:2212
const RC_NEW
Definition: Defines.php:123
const DB_REPLICA
Definition: defines.php:25
run( $resultPageSet=null)
const DELETED_ACTION
Definition: LogPage.php:34
const PARAM_MIN
(integer) Lowest value allowed for the parameter, for PARAM_TYPE &#39;integer&#39; and &#39;limit&#39;.
Definition: ApiBase.php:106
requireMaxOneParameter( $params,... $required)
Die if more than one of a certain set of parameters is set and not false.
Definition: ApiBase.php:928
const PRC_AUTOPATROLLED
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
const RC_LOG
Definition: Defines.php:124