3 use MediaWiki\Linker\LinkTarget
;
4 use Wikimedia\Assert\Assert
;
7 * Class performing complex database queries related to WatchedItems.
14 * @license GNU GPL v2+
16 class WatchedItemQueryService
{
18 const DIR_OLDER
= 'older';
19 const DIR_NEWER
= 'newer';
21 const INCLUDE_FLAGS
= 'flags';
22 const INCLUDE_USER
= 'user';
23 const INCLUDE_USER_ID
= 'userid';
24 const INCLUDE_COMMENT
= 'comment';
25 const INCLUDE_PATROL_INFO
= 'patrol';
26 const INCLUDE_SIZES
= 'sizes';
27 const INCLUDE_LOG_INFO
= 'loginfo';
29 // FILTER_* constants are part of public API (are used in ApiQueryWatchlist and
30 // ApiQueryWatchlistRaw classes) and should not be changed.
31 // Changing values of those constants will result in a breaking change in the API
32 const FILTER_MINOR
= 'minor';
33 const FILTER_NOT_MINOR
= '!minor';
34 const FILTER_BOT
= 'bot';
35 const FILTER_NOT_BOT
= '!bot';
36 const FILTER_ANON
= 'anon';
37 const FILTER_NOT_ANON
= '!anon';
38 const FILTER_PATROLLED
= 'patrolled';
39 const FILTER_NOT_PATROLLED
= '!patrolled';
40 const FILTER_UNREAD
= 'unread';
41 const FILTER_NOT_UNREAD
= '!unread';
42 const FILTER_CHANGED
= 'changed';
43 const FILTER_NOT_CHANGED
= '!changed';
45 const SORT_ASC
= 'ASC';
46 const SORT_DESC
= 'DESC';
51 private $loadBalancer;
53 public function __construct( LoadBalancer
$loadBalancer ) {
54 $this->loadBalancer
= $loadBalancer;
61 private function getConnection() {
62 return $this->loadBalancer
->getConnectionRef( DB_REPLICA
, [ 'watchlist' ] );
67 * @param array $options Allowed keys:
68 * 'includeFields' => string[] RecentChange fields to be included in the result,
69 * self::INCLUDE_* constants should be used
70 * 'filters' => string[] optional filters to narrow down resulted items
71 * 'namespaceIds' => int[] optional namespace IDs to filter by
72 * (defaults to all namespaces)
73 * 'allRevisions' => bool return multiple revisions of the same page if true,
74 * only the most recent if false (default)
75 * 'rcTypes' => int[] which types of RecentChanges to include
76 * (defaults to all types), allowed values: RC_EDIT, RC_NEW,
77 * RC_LOG, RC_EXTERNAL, RC_CATEGORIZE
78 * 'onlyByUser' => string only list changes by a specified user
79 * 'notByUser' => string do not incluide changes by a specified user
80 * 'dir' => string in which direction to enumerate, accepted values:
81 * - DIR_OLDER list newest first
82 * - DIR_NEWER list oldest first
83 * 'start' => string (format accepted by wfTimestamp) requires 'dir' option,
84 * timestamp to start enumerating from
85 * 'end' => string (format accepted by wfTimestamp) requires 'dir' option,
86 * timestamp to end enumerating
87 * 'startFrom' => [ string $rcTimestamp, int $rcId ] requires 'dir' option,
88 * return items starting from the RecentChange specified by this,
89 * $rcTimestamp should be in the format accepted by wfTimestamp
90 * 'watchlistOwner' => User user whose watchlist items should be listed if different
91 * than the one specified with $user param,
92 * requires 'watchlistOwnerToken' option
93 * 'watchlistOwnerToken' => string a watchlist token used to access another user's
94 * watchlist, used with 'watchlistOwnerToken' option
95 * 'limit' => int maximum numbers of items to return
96 * 'usedInGenerator' => bool include only RecentChange id field required by the
97 * generator ('rc_cur_id' or 'rc_this_oldid') if true, or all
98 * id fields ('rc_cur_id', 'rc_this_oldid', 'rc_last_oldid')
100 * @return array of pairs ( WatchedItem $watchedItem, string[] $recentChangeInfo ),
101 * where $recentChangeInfo contains the following keys:
108 * Additional keys could be added by specifying the 'includeFields' option
110 public function getWatchedItemsWithRecentChangeInfo( User
$user, array $options = [] ) {
112 'includeFields' => [],
113 'namespaceIds' => [],
115 'allRevisions' => false,
116 'usedInGenerator' => false
120 !isset( $options['rcTypes'] )
121 ||
!array_diff( $options['rcTypes'], [ RC_EDIT
, RC_NEW
, RC_LOG
, RC_EXTERNAL
, RC_CATEGORIZE
] ),
122 '$options[\'rcTypes\']',
123 'must be an array containing only: RC_EDIT, RC_NEW, RC_LOG, RC_EXTERNAL and/or RC_CATEGORIZE'
126 !isset( $options['dir'] ) ||
in_array( $options['dir'], [ self
::DIR_OLDER
, self
::DIR_NEWER
] ),
128 'must be DIR_OLDER or DIR_NEWER'
131 !isset( $options['start'] ) && !isset( $options['end'] ) && !isset( $options['startFrom'] )
132 ||
isset( $options['dir'] ),
134 'must be provided when providing any of options: start, end, startFrom'
137 !isset( $options['startFrom'] )
138 ||
( is_array( $options['startFrom'] ) && count( $options['startFrom'] ) === 2 ),
139 '$options[\'startFrom\']',
140 'must be a two-element array'
142 if ( array_key_exists( 'watchlistOwner', $options ) ) {
143 Assert
::parameterType(
145 $options['watchlistOwner'],
146 '$options[\'watchlistOwner\']'
149 isset( $options['watchlistOwnerToken'] ),
150 '$options[\'watchlistOwnerToken\']',
151 'must be provided when providing watchlistOwner option'
155 $tables = [ 'recentchanges', 'watchlist' ];
156 if ( !$options['allRevisions'] ) {
160 $db = $this->getConnection();
162 $fields = $this->getWatchedItemsWithRCInfoQueryFields( $options );
163 $conds = $this->getWatchedItemsWithRCInfoQueryConds( $db, $user, $options );
164 $dbOptions = $this->getWatchedItemsWithRCInfoQueryDbOptions( $options );
165 $joinConds = $this->getWatchedItemsWithRCInfoQueryJoinConds( $options );
177 foreach ( $res as $row ) {
181 new TitleValue( (int)$row->rc_namespace
, $row->rc_title
),
182 $row->wl_notificationtimestamp
184 $this->getRecentChangeFieldsFromRow( $row )
192 * For simple listing of user's watchlist items, see WatchedItemStore::getWatchedItemsForUser
195 * @param array $options Allowed keys:
196 * 'sort' => string optional sorting by namespace ID and title
197 * one of the self::SORT_* constants
198 * 'namespaceIds' => int[] optional namespace IDs to filter by (defaults to all namespaces)
199 * 'limit' => int maximum number of items to return
200 * 'filter' => string optional filter, one of the self::FILTER_* contants
201 * 'from' => LinkTarget requires 'sort' key, only return items starting from
202 * those related to the link target
203 * 'until' => LinkTarget requires 'sort' key, only return items until
204 * those related to the link target
205 * 'startFrom' => LinkTarget requires 'sort' key, only return items starting from
206 * those related to the link target, allows to skip some link targets
207 * specified using the form option
208 * @return WatchedItem[]
210 public function getWatchedItemsForUser( User
$user, array $options = [] ) {
211 if ( $user->isAnon() ) {
212 // TODO: should this just return an empty array or rather complain loud at this point
213 // as e.g. ApiBase::getWatchlistUser does?
217 $options +
= [ 'namespaceIds' => [] ];
220 !isset( $options['sort'] ) ||
in_array( $options['sort'], [ self
::SORT_ASC
, self
::SORT_DESC
] ),
221 '$options[\'sort\']',
222 'must be SORT_ASC or SORT_DESC'
225 !isset( $options['filter'] ) ||
in_array(
226 $options['filter'], [ self
::FILTER_CHANGED
, self
::FILTER_NOT_CHANGED
]
228 '$options[\'filter\']',
229 'must be FILTER_CHANGED or FILTER_NOT_CHANGED'
232 !isset( $options['from'] ) && !isset( $options['until'] ) && !isset( $options['startFrom'] )
233 ||
isset( $options['sort'] ),
234 '$options[\'sort\']',
235 'must be provided if any of "from", "until", "startFrom" options is provided'
238 $db = $this->getConnection();
240 $conds = $this->getWatchedItemsForUserQueryConds( $db, $user, $options );
241 $dbOptions = $this->getWatchedItemsForUserQueryDbOptions( $options );
245 [ 'wl_namespace', 'wl_title', 'wl_notificationtimestamp' ],
252 foreach ( $res as $row ) {
253 // todo these could all be cached at some point?
254 $watchedItems[] = new WatchedItem(
256 new TitleValue( (int)$row->wl_namespace
, $row->wl_title
),
257 $row->wl_notificationtimestamp
261 return $watchedItems;
264 private function getRecentChangeFieldsFromRow( stdClass
$row ) {
265 // This can be simplified to single array_filter call filtering by key value,
266 // once we stop supporting PHP 5.5
267 $allFields = get_object_vars( $row );
268 $rcKeys = array_filter(
269 array_keys( $allFields ),
271 return substr( $key, 0, 3 ) === 'rc_';
274 return array_intersect_key( $allFields, array_flip( $rcKeys ) );
277 private function getWatchedItemsWithRCInfoQueryFields( array $options ) {
285 'wl_notificationtimestamp'
293 if ( $options['usedInGenerator'] ) {
294 if ( $options['allRevisions'] ) {
295 $rcIdFields = [ 'rc_this_oldid' ];
297 $rcIdFields = [ 'rc_cur_id' ];
300 $fields = array_merge( $fields, $rcIdFields );
302 if ( in_array( self
::INCLUDE_FLAGS
, $options['includeFields'] ) ) {
303 $fields = array_merge( $fields, [ 'rc_type', 'rc_minor', 'rc_bot' ] );
305 if ( in_array( self
::INCLUDE_USER
, $options['includeFields'] ) ) {
306 $fields[] = 'rc_user_text';
308 if ( in_array( self
::INCLUDE_USER_ID
, $options['includeFields'] ) ) {
309 $fields[] = 'rc_user';
311 if ( in_array( self
::INCLUDE_COMMENT
, $options['includeFields'] ) ) {
312 $fields[] = 'rc_comment';
314 if ( in_array( self
::INCLUDE_PATROL_INFO
, $options['includeFields'] ) ) {
315 $fields = array_merge( $fields, [ 'rc_patrolled', 'rc_log_type' ] );
317 if ( in_array( self
::INCLUDE_SIZES
, $options['includeFields'] ) ) {
318 $fields = array_merge( $fields, [ 'rc_old_len', 'rc_new_len' ] );
320 if ( in_array( self
::INCLUDE_LOG_INFO
, $options['includeFields'] ) ) {
321 $fields = array_merge( $fields, [ 'rc_logid', 'rc_log_type', 'rc_log_action', 'rc_params' ] );
327 private function getWatchedItemsWithRCInfoQueryConds(
332 $watchlistOwnerId = $this->getWatchlistOwnerId( $user, $options );
333 $conds = [ 'wl_user' => $watchlistOwnerId ];
335 if ( !$options['allRevisions'] ) {
336 $conds[] = $db->makeList(
337 [ 'rc_this_oldid=page_latest', 'rc_type=' . RC_LOG
],
342 if ( $options['namespaceIds'] ) {
343 $conds['wl_namespace'] = array_map( 'intval', $options['namespaceIds'] );
346 if ( array_key_exists( 'rcTypes', $options ) ) {
347 $conds['rc_type'] = array_map( 'intval', $options['rcTypes'] );
350 $conds = array_merge(
352 $this->getWatchedItemsWithRCInfoQueryFilterConds( $user, $options )
355 $conds = array_merge( $conds, $this->getStartEndConds( $db, $options ) );
357 if ( !isset( $options['start'] ) && !isset( $options['end'] ) ) {
358 if ( $db->getType() === 'mysql' ) {
359 // This is an index optimization for mysql
360 $conds[] = "rc_timestamp > ''";
364 $conds = array_merge( $conds, $this->getUserRelatedConds( $db, $user, $options ) );
366 $deletedPageLogCond = $this->getExtraDeletedPageLogEntryRelatedCond( $db, $user );
367 if ( $deletedPageLogCond ) {
368 $conds[] = $deletedPageLogCond;
371 if ( array_key_exists( 'startFrom', $options ) ) {
372 $conds[] = $this->getStartFromConds( $db, $options );
378 private function getWatchlistOwnerId( User
$user, array $options ) {
379 if ( array_key_exists( 'watchlistOwner', $options ) ) {
380 /** @var User $watchlistOwner */
381 $watchlistOwner = $options['watchlistOwner'];
382 $ownersToken = $watchlistOwner->getOption( 'watchlisttoken' );
383 $token = $options['watchlistOwnerToken'];
384 if ( $ownersToken == '' ||
!hash_equals( $ownersToken, $token ) ) {
385 throw new UsageException(
386 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences',
390 return $watchlistOwner->getId();
392 return $user->getId();
395 private function getWatchedItemsWithRCInfoQueryFilterConds( User
$user, array $options ) {
398 if ( in_array( self
::FILTER_MINOR
, $options['filters'] ) ) {
399 $conds[] = 'rc_minor != 0';
400 } elseif ( in_array( self
::FILTER_NOT_MINOR
, $options['filters'] ) ) {
401 $conds[] = 'rc_minor = 0';
404 if ( in_array( self
::FILTER_BOT
, $options['filters'] ) ) {
405 $conds[] = 'rc_bot != 0';
406 } elseif ( in_array( self
::FILTER_NOT_BOT
, $options['filters'] ) ) {
407 $conds[] = 'rc_bot = 0';
410 if ( in_array( self
::FILTER_ANON
, $options['filters'] ) ) {
411 $conds[] = 'rc_user = 0';
412 } elseif ( in_array( self
::FILTER_NOT_ANON
, $options['filters'] ) ) {
413 $conds[] = 'rc_user != 0';
416 if ( $user->useRCPatrol() ||
$user->useNPPatrol() ) {
417 // TODO: not sure if this should simply ignore patrolled filters if user does not have the patrol
418 // right, or maybe rather fail loud at this point, same as e.g. ApiQueryWatchlist does?
419 if ( in_array( self
::FILTER_PATROLLED
, $options['filters'] ) ) {
420 $conds[] = 'rc_patrolled != 0';
421 } elseif ( in_array( self
::FILTER_NOT_PATROLLED
, $options['filters'] ) ) {
422 $conds[] = 'rc_patrolled = 0';
426 if ( in_array( self
::FILTER_UNREAD
, $options['filters'] ) ) {
427 $conds[] = 'rc_timestamp >= wl_notificationtimestamp';
428 } elseif ( in_array( self
::FILTER_NOT_UNREAD
, $options['filters'] ) ) {
429 // TODO: should this be changed to use Database::makeList?
430 $conds[] = 'wl_notificationtimestamp IS NULL OR rc_timestamp < wl_notificationtimestamp';
436 private function getStartEndConds( IDatabase
$db, array $options ) {
437 if ( !isset( $options['start'] ) && ! isset( $options['end'] ) ) {
443 if ( isset( $options['start'] ) ) {
444 $after = $options['dir'] === self
::DIR_OLDER ?
'<=' : '>=';
445 $conds[] = 'rc_timestamp ' . $after . ' ' .
446 $db->addQuotes( $db->timestamp( $options['start'] ) );
448 if ( isset( $options['end'] ) ) {
449 $before = $options['dir'] === self
::DIR_OLDER ?
'>=' : '<=';
450 $conds[] = 'rc_timestamp ' . $before . ' ' .
451 $db->addQuotes( $db->timestamp( $options['end'] ) );
457 private function getUserRelatedConds( IDatabase
$db, User
$user, array $options ) {
458 if ( !array_key_exists( 'onlyByUser', $options ) && !array_key_exists( 'notByUser', $options ) ) {
464 if ( array_key_exists( 'onlyByUser', $options ) ) {
465 $conds['rc_user_text'] = $options['onlyByUser'];
466 } elseif ( array_key_exists( 'notByUser', $options ) ) {
467 $conds[] = 'rc_user_text != ' . $db->addQuotes( $options['notByUser'] );
470 // Avoid brute force searches (bug 17342)
472 if ( !$user->isAllowed( 'deletedhistory' ) ) {
473 $bitmask = Revision
::DELETED_USER
;
474 } elseif ( !$user->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
475 $bitmask = Revision
::DELETED_USER | Revision
::DELETED_RESTRICTED
;
478 $conds[] = $db->bitAnd( 'rc_deleted', $bitmask ) . " != $bitmask";
484 private function getExtraDeletedPageLogEntryRelatedCond( IDatabase
$db, User
$user ) {
485 // LogPage::DELETED_ACTION hides the affected page, too. So hide those
486 // entirely from the watchlist, or someone could guess the title.
488 if ( !$user->isAllowed( 'deletedhistory' ) ) {
489 $bitmask = LogPage
::DELETED_ACTION
;
490 } elseif ( !$user->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
491 $bitmask = LogPage
::DELETED_ACTION | LogPage
::DELETED_RESTRICTED
;
494 return $db->makeList( [
495 'rc_type != ' . RC_LOG
,
496 $db->bitAnd( 'rc_deleted', $bitmask ) . " != $bitmask",
502 private function getStartFromConds( IDatabase
$db, array $options ) {
503 $op = $options['dir'] === self
::DIR_OLDER ?
'<' : '>';
504 list( $rcTimestamp, $rcId ) = $options['startFrom'];
505 $rcTimestamp = $db->addQuotes( $db->timestamp( $rcTimestamp ) );
507 return $db->makeList(
509 "rc_timestamp $op $rcTimestamp",
512 "rc_timestamp = $rcTimestamp",
522 private function getWatchedItemsForUserQueryConds( IDatabase
$db, User
$user, array $options ) {
523 $conds = [ 'wl_user' => $user->getId() ];
524 if ( $options['namespaceIds'] ) {
525 $conds['wl_namespace'] = array_map( 'intval', $options['namespaceIds'] );
527 if ( isset( $options['filter'] ) ) {
528 $filter = $options['filter'];
529 if ( $filter === self
::FILTER_CHANGED
) {
530 $conds[] = 'wl_notificationtimestamp IS NOT NULL';
532 $conds[] = 'wl_notificationtimestamp IS NULL';
536 if ( isset( $options['from'] ) ) {
537 $op = $options['sort'] === self
::SORT_ASC ?
'>' : '<';
538 $conds[] = $this->getFromUntilTargetConds( $db, $options['from'], $op );
540 if ( isset( $options['until'] ) ) {
541 $op = $options['sort'] === self
::SORT_ASC ?
'<' : '>';
542 $conds[] = $this->getFromUntilTargetConds( $db, $options['until'], $op );
544 if ( isset( $options['startFrom'] ) ) {
545 $op = $options['sort'] === self
::SORT_ASC ?
'>' : '<';
546 $conds[] = $this->getFromUntilTargetConds( $db, $options['startFrom'], $op );
553 * Creates a query condition part for getting only items before or after the given link target
554 * (while ordering using $sort mode)
556 * @param IDatabase $db
557 * @param LinkTarget $target
558 * @param string $op comparison operator to use in the conditions
561 private function getFromUntilTargetConds( IDatabase
$db, LinkTarget
$target, $op ) {
562 return $db->makeList(
564 "wl_namespace $op " . $target->getNamespace(),
567 'wl_namespace = ' . $target->getNamespace(),
568 "wl_title $op= " . $db->addQuotes( $target->getDBkey() )
577 private function getWatchedItemsWithRCInfoQueryDbOptions( array $options ) {
580 if ( array_key_exists( 'dir', $options ) ) {
581 $sort = $options['dir'] === self
::DIR_OLDER ?
' DESC' : '';
582 $dbOptions['ORDER BY'] = [ 'rc_timestamp' . $sort, 'rc_id' . $sort ];
585 if ( array_key_exists( 'limit', $options ) ) {
586 $dbOptions['LIMIT'] = (int)$options['limit'];
592 private function getWatchedItemsForUserQueryDbOptions( array $options ) {
594 if ( array_key_exists( 'sort', $options ) ) {
595 $dbOptions['ORDER BY'] = [
596 "wl_namespace {$options['sort']}",
597 "wl_title {$options['sort']}"
599 if ( count( $options['namespaceIds'] ) === 1 ) {
600 $dbOptions['ORDER BY'] = "wl_title {$options['sort']}";
603 if ( array_key_exists( 'limit', $options ) ) {
604 $dbOptions['LIMIT'] = (int)$options['limit'];
609 private function getWatchedItemsWithRCInfoQueryJoinConds( array $options ) {
611 'watchlist' => [ 'INNER JOIN',
613 'wl_namespace=rc_namespace',
618 if ( !$options['allRevisions'] ) {
619 $joinConds['page'] = [ 'LEFT JOIN', 'rc_cur_id=page_id' ];