3 use Wikimedia\Rdbms\IDatabase
;
4 use MediaWiki\Linker\LinkTarget
;
5 use Wikimedia\Assert\Assert
;
6 use Wikimedia\Rdbms\LoadBalancer
;
9 * Class performing complex database queries related to WatchedItems.
16 * @license GNU GPL v2+
18 class WatchedItemQueryService
{
20 const DIR_OLDER
= 'older';
21 const DIR_NEWER
= 'newer';
23 const INCLUDE_FLAGS
= 'flags';
24 const INCLUDE_USER
= 'user';
25 const INCLUDE_USER_ID
= 'userid';
26 const INCLUDE_COMMENT
= 'comment';
27 const INCLUDE_PATROL_INFO
= 'patrol';
28 const INCLUDE_SIZES
= 'sizes';
29 const INCLUDE_LOG_INFO
= 'loginfo';
30 const INCLUDE_TAGS
= 'tags';
32 // FILTER_* constants are part of public API (are used in ApiQueryWatchlist and
33 // ApiQueryWatchlistRaw classes) and should not be changed.
34 // Changing values of those constants will result in a breaking change in the API
35 const FILTER_MINOR
= 'minor';
36 const FILTER_NOT_MINOR
= '!minor';
37 const FILTER_BOT
= 'bot';
38 const FILTER_NOT_BOT
= '!bot';
39 const FILTER_ANON
= 'anon';
40 const FILTER_NOT_ANON
= '!anon';
41 const FILTER_PATROLLED
= 'patrolled';
42 const FILTER_NOT_PATROLLED
= '!patrolled';
43 const FILTER_UNREAD
= 'unread';
44 const FILTER_NOT_UNREAD
= '!unread';
45 const FILTER_CHANGED
= 'changed';
46 const FILTER_NOT_CHANGED
= '!changed';
48 const SORT_ASC
= 'ASC';
49 const SORT_DESC
= 'DESC';
54 private $loadBalancer;
56 /** @var WatchedItemQueryServiceExtension[]|null */
57 private $extensions = null;
59 /** @var CommentStore */
60 private $commentStore;
62 public function __construct(
63 LoadBalancer
$loadBalancer,
64 CommentStore
$commentStore
66 $this->loadBalancer
= $loadBalancer;
67 $this->commentStore
= $commentStore;
71 * @return WatchedItemQueryServiceExtension[]
73 private function getExtensions() {
74 if ( $this->extensions
=== null ) {
75 $this->extensions
= [];
76 Hooks
::run( 'WatchedItemQueryServiceExtensions', [ &$this->extensions
, $this ] );
78 return $this->extensions
;
85 private function getConnection() {
86 return $this->loadBalancer
->getConnectionRef( DB_REPLICA
, [ 'watchlist' ] );
91 * @param array $options Allowed keys:
92 * 'includeFields' => string[] RecentChange fields to be included in the result,
93 * self::INCLUDE_* constants should be used
94 * 'filters' => string[] optional filters to narrow down resulted items
95 * 'namespaceIds' => int[] optional namespace IDs to filter by
96 * (defaults to all namespaces)
97 * 'allRevisions' => bool return multiple revisions of the same page if true,
98 * only the most recent if false (default)
99 * 'rcTypes' => int[] which types of RecentChanges to include
100 * (defaults to all types), allowed values: RC_EDIT, RC_NEW,
101 * RC_LOG, RC_EXTERNAL, RC_CATEGORIZE
102 * 'onlyByUser' => string only list changes by a specified user
103 * 'notByUser' => string do not incluide changes by a specified user
104 * 'dir' => string in which direction to enumerate, accepted values:
105 * - DIR_OLDER list newest first
106 * - DIR_NEWER list oldest first
107 * 'start' => string (format accepted by wfTimestamp) requires 'dir' option,
108 * timestamp to start enumerating from
109 * 'end' => string (format accepted by wfTimestamp) requires 'dir' option,
110 * timestamp to end enumerating
111 * 'watchlistOwner' => User user whose watchlist items should be listed if different
112 * than the one specified with $user param,
113 * requires 'watchlistOwnerToken' option
114 * 'watchlistOwnerToken' => string a watchlist token used to access another user's
115 * watchlist, used with 'watchlistOwnerToken' option
116 * 'limit' => int maximum numbers of items to return
117 * 'usedInGenerator' => bool include only RecentChange id field required by the
118 * generator ('rc_cur_id' or 'rc_this_oldid') if true, or all
119 * id fields ('rc_cur_id', 'rc_this_oldid', 'rc_last_oldid')
121 * @param array|null &$startFrom Continuation value: [ string $rcTimestamp, int $rcId ]
122 * @return array of pairs ( WatchedItem $watchedItem, string[] $recentChangeInfo ),
123 * where $recentChangeInfo contains the following keys:
130 * Additional keys could be added by specifying the 'includeFields' option
132 public function getWatchedItemsWithRecentChangeInfo(
133 User
$user, array $options = [], &$startFrom = null
136 'includeFields' => [],
137 'namespaceIds' => [],
139 'allRevisions' => false,
140 'usedInGenerator' => false
144 !isset( $options['rcTypes'] )
145 ||
!array_diff( $options['rcTypes'], [ RC_EDIT
, RC_NEW
, RC_LOG
, RC_EXTERNAL
, RC_CATEGORIZE
] ),
146 '$options[\'rcTypes\']',
147 'must be an array containing only: RC_EDIT, RC_NEW, RC_LOG, RC_EXTERNAL and/or RC_CATEGORIZE'
150 !isset( $options['dir'] ) ||
in_array( $options['dir'], [ self
::DIR_OLDER
, self
::DIR_NEWER
] ),
152 'must be DIR_OLDER or DIR_NEWER'
155 !isset( $options['start'] ) && !isset( $options['end'] ) && $startFrom === null
156 ||
isset( $options['dir'] ),
158 'must be provided when providing the "start" or "end" options or the $startFrom parameter'
161 !isset( $options['startFrom'] ),
162 '$options[\'startFrom\']',
163 'must not be provided, use $startFrom instead'
166 !isset( $startFrom ) ||
( is_array( $startFrom ) && count( $startFrom ) === 2 ),
168 'must be a two-element array'
170 if ( array_key_exists( 'watchlistOwner', $options ) ) {
171 Assert
::parameterType(
173 $options['watchlistOwner'],
174 '$options[\'watchlistOwner\']'
177 isset( $options['watchlistOwnerToken'] ),
178 '$options[\'watchlistOwnerToken\']',
179 'must be provided when providing watchlistOwner option'
183 $db = $this->getConnection();
185 $tables = $this->getWatchedItemsWithRCInfoQueryTables( $options );
186 $fields = $this->getWatchedItemsWithRCInfoQueryFields( $options );
187 $conds = $this->getWatchedItemsWithRCInfoQueryConds( $db, $user, $options );
188 $dbOptions = $this->getWatchedItemsWithRCInfoQueryDbOptions( $options );
189 $joinConds = $this->getWatchedItemsWithRCInfoQueryJoinConds( $options );
191 if ( $startFrom !== null ) {
192 $conds[] = $this->getStartFromConds( $db, $options, $startFrom );
195 foreach ( $this->getExtensions() as $extension ) {
196 $extension->modifyWatchedItemsWithRCInfoQuery(
197 $user, $options, $db,
215 $limit = isset( $dbOptions['LIMIT'] ) ?
$dbOptions['LIMIT'] : INF
;
218 foreach ( $res as $row ) {
219 if ( --$limit <= 0 ) {
220 $startFrom = [ $row->rc_timestamp
, $row->rc_id
];
227 new TitleValue( (int)$row->rc_namespace
, $row->rc_title
),
228 $row->wl_notificationtimestamp
230 $this->getRecentChangeFieldsFromRow( $row )
234 foreach ( $this->getExtensions() as $extension ) {
235 $extension->modifyWatchedItemsWithRCInfo( $user, $options, $db, $items, $res, $startFrom );
242 * For simple listing of user's watchlist items, see WatchedItemStore::getWatchedItemsForUser
245 * @param array $options Allowed keys:
246 * 'sort' => string optional sorting by namespace ID and title
247 * one of the self::SORT_* constants
248 * 'namespaceIds' => int[] optional namespace IDs to filter by (defaults to all namespaces)
249 * 'limit' => int maximum number of items to return
250 * 'filter' => string optional filter, one of the self::FILTER_* contants
251 * 'from' => LinkTarget requires 'sort' key, only return items starting from
252 * those related to the link target
253 * 'until' => LinkTarget requires 'sort' key, only return items until
254 * those related to the link target
255 * 'startFrom' => LinkTarget requires 'sort' key, only return items starting from
256 * those related to the link target, allows to skip some link targets
257 * specified using the form option
258 * @return WatchedItem[]
260 public function getWatchedItemsForUser( User
$user, array $options = [] ) {
261 if ( $user->isAnon() ) {
262 // TODO: should this just return an empty array or rather complain loud at this point
263 // as e.g. ApiBase::getWatchlistUser does?
267 $options +
= [ 'namespaceIds' => [] ];
270 !isset( $options['sort'] ) ||
in_array( $options['sort'], [ self
::SORT_ASC
, self
::SORT_DESC
] ),
271 '$options[\'sort\']',
272 'must be SORT_ASC or SORT_DESC'
275 !isset( $options['filter'] ) ||
in_array(
276 $options['filter'], [ self
::FILTER_CHANGED
, self
::FILTER_NOT_CHANGED
]
278 '$options[\'filter\']',
279 'must be FILTER_CHANGED or FILTER_NOT_CHANGED'
282 !isset( $options['from'] ) && !isset( $options['until'] ) && !isset( $options['startFrom'] )
283 ||
isset( $options['sort'] ),
284 '$options[\'sort\']',
285 'must be provided if any of "from", "until", "startFrom" options is provided'
288 $db = $this->getConnection();
290 $conds = $this->getWatchedItemsForUserQueryConds( $db, $user, $options );
291 $dbOptions = $this->getWatchedItemsForUserQueryDbOptions( $options );
295 [ 'wl_namespace', 'wl_title', 'wl_notificationtimestamp' ],
302 foreach ( $res as $row ) {
303 // todo these could all be cached at some point?
304 $watchedItems[] = new WatchedItem(
306 new TitleValue( (int)$row->wl_namespace
, $row->wl_title
),
307 $row->wl_notificationtimestamp
311 return $watchedItems;
314 private function getRecentChangeFieldsFromRow( stdClass
$row ) {
315 // This can be simplified to single array_filter call filtering by key value,
316 // once we stop supporting PHP 5.5
317 $allFields = get_object_vars( $row );
318 $rcKeys = array_filter(
319 array_keys( $allFields ),
321 return substr( $key, 0, 3 ) === 'rc_';
324 return array_intersect_key( $allFields, array_flip( $rcKeys ) );
327 private function getWatchedItemsWithRCInfoQueryTables( array $options ) {
328 $tables = [ 'recentchanges', 'watchlist' ];
329 if ( !$options['allRevisions'] ) {
332 if ( in_array( self
::INCLUDE_COMMENT
, $options['includeFields'] ) ) {
333 $tables +
= $this->commentStore
->getJoin( 'rc_comment' )['tables'];
335 if ( in_array( self
::INCLUDE_TAGS
, $options['includeFields'] ) ) {
336 $tables[] = 'tag_summary';
341 private function getWatchedItemsWithRCInfoQueryFields( array $options ) {
349 'wl_notificationtimestamp'
357 if ( $options['usedInGenerator'] ) {
358 if ( $options['allRevisions'] ) {
359 $rcIdFields = [ 'rc_this_oldid' ];
361 $rcIdFields = [ 'rc_cur_id' ];
364 $fields = array_merge( $fields, $rcIdFields );
366 if ( in_array( self
::INCLUDE_FLAGS
, $options['includeFields'] ) ) {
367 $fields = array_merge( $fields, [ 'rc_type', 'rc_minor', 'rc_bot' ] );
369 if ( in_array( self
::INCLUDE_USER
, $options['includeFields'] ) ) {
370 $fields[] = 'rc_user_text';
372 if ( in_array( self
::INCLUDE_USER_ID
, $options['includeFields'] ) ) {
373 $fields[] = 'rc_user';
375 if ( in_array( self
::INCLUDE_COMMENT
, $options['includeFields'] ) ) {
376 $fields +
= $this->commentStore
->getJoin( 'rc_comment' )['fields'];
378 if ( in_array( self
::INCLUDE_PATROL_INFO
, $options['includeFields'] ) ) {
379 $fields = array_merge( $fields, [ 'rc_patrolled', 'rc_log_type' ] );
381 if ( in_array( self
::INCLUDE_SIZES
, $options['includeFields'] ) ) {
382 $fields = array_merge( $fields, [ 'rc_old_len', 'rc_new_len' ] );
384 if ( in_array( self
::INCLUDE_LOG_INFO
, $options['includeFields'] ) ) {
385 $fields = array_merge( $fields, [ 'rc_logid', 'rc_log_type', 'rc_log_action', 'rc_params' ] );
387 if ( in_array( self
::INCLUDE_TAGS
, $options['includeFields'] ) ) {
388 // prefixed with rc_ to include the field in getRecentChangeFieldsFromRow
389 $fields['rc_tags'] = 'ts_tags';
395 private function getWatchedItemsWithRCInfoQueryConds(
400 $watchlistOwnerId = $this->getWatchlistOwnerId( $user, $options );
401 $conds = [ 'wl_user' => $watchlistOwnerId ];
403 if ( !$options['allRevisions'] ) {
404 $conds[] = $db->makeList(
405 [ 'rc_this_oldid=page_latest', 'rc_type=' . RC_LOG
],
410 if ( $options['namespaceIds'] ) {
411 $conds['wl_namespace'] = array_map( 'intval', $options['namespaceIds'] );
414 if ( array_key_exists( 'rcTypes', $options ) ) {
415 $conds['rc_type'] = array_map( 'intval', $options['rcTypes'] );
418 $conds = array_merge(
420 $this->getWatchedItemsWithRCInfoQueryFilterConds( $user, $options )
423 $conds = array_merge( $conds, $this->getStartEndConds( $db, $options ) );
425 if ( !isset( $options['start'] ) && !isset( $options['end'] ) ) {
426 if ( $db->getType() === 'mysql' ) {
427 // This is an index optimization for mysql
428 $conds[] = 'rc_timestamp > ' . $db->addQuotes( '' );
432 $conds = array_merge( $conds, $this->getUserRelatedConds( $db, $user, $options ) );
434 $deletedPageLogCond = $this->getExtraDeletedPageLogEntryRelatedCond( $db, $user );
435 if ( $deletedPageLogCond ) {
436 $conds[] = $deletedPageLogCond;
442 private function getWatchlistOwnerId( User
$user, array $options ) {
443 if ( array_key_exists( 'watchlistOwner', $options ) ) {
444 /** @var User $watchlistOwner */
445 $watchlistOwner = $options['watchlistOwner'];
446 $ownersToken = $watchlistOwner->getOption( 'watchlisttoken' );
447 $token = $options['watchlistOwnerToken'];
448 if ( $ownersToken == '' ||
!hash_equals( $ownersToken, $token ) ) {
449 throw ApiUsageException
::newWithMessage( null, 'apierror-bad-watchlist-token', 'bad_wltoken' );
451 return $watchlistOwner->getId();
453 return $user->getId();
456 private function getWatchedItemsWithRCInfoQueryFilterConds( User
$user, array $options ) {
459 if ( in_array( self
::FILTER_MINOR
, $options['filters'] ) ) {
460 $conds[] = 'rc_minor != 0';
461 } elseif ( in_array( self
::FILTER_NOT_MINOR
, $options['filters'] ) ) {
462 $conds[] = 'rc_minor = 0';
465 if ( in_array( self
::FILTER_BOT
, $options['filters'] ) ) {
466 $conds[] = 'rc_bot != 0';
467 } elseif ( in_array( self
::FILTER_NOT_BOT
, $options['filters'] ) ) {
468 $conds[] = 'rc_bot = 0';
471 if ( in_array( self
::FILTER_ANON
, $options['filters'] ) ) {
472 $conds[] = 'rc_user = 0';
473 } elseif ( in_array( self
::FILTER_NOT_ANON
, $options['filters'] ) ) {
474 $conds[] = 'rc_user != 0';
477 if ( $user->useRCPatrol() ||
$user->useNPPatrol() ) {
478 // TODO: not sure if this should simply ignore patrolled filters if user does not have the patrol
479 // right, or maybe rather fail loud at this point, same as e.g. ApiQueryWatchlist does?
480 if ( in_array( self
::FILTER_PATROLLED
, $options['filters'] ) ) {
481 $conds[] = 'rc_patrolled != 0';
482 } elseif ( in_array( self
::FILTER_NOT_PATROLLED
, $options['filters'] ) ) {
483 $conds[] = 'rc_patrolled = 0';
487 if ( in_array( self
::FILTER_UNREAD
, $options['filters'] ) ) {
488 $conds[] = 'rc_timestamp >= wl_notificationtimestamp';
489 } elseif ( in_array( self
::FILTER_NOT_UNREAD
, $options['filters'] ) ) {
490 // TODO: should this be changed to use Database::makeList?
491 $conds[] = 'wl_notificationtimestamp IS NULL OR rc_timestamp < wl_notificationtimestamp';
497 private function getStartEndConds( IDatabase
$db, array $options ) {
498 if ( !isset( $options['start'] ) && !isset( $options['end'] ) ) {
504 if ( isset( $options['start'] ) ) {
505 $after = $options['dir'] === self
::DIR_OLDER ?
'<=' : '>=';
506 $conds[] = 'rc_timestamp ' . $after . ' ' .
507 $db->addQuotes( $db->timestamp( $options['start'] ) );
509 if ( isset( $options['end'] ) ) {
510 $before = $options['dir'] === self
::DIR_OLDER ?
'>=' : '<=';
511 $conds[] = 'rc_timestamp ' . $before . ' ' .
512 $db->addQuotes( $db->timestamp( $options['end'] ) );
518 private function getUserRelatedConds( IDatabase
$db, User
$user, array $options ) {
519 if ( !array_key_exists( 'onlyByUser', $options ) && !array_key_exists( 'notByUser', $options ) ) {
525 if ( array_key_exists( 'onlyByUser', $options ) ) {
526 $conds['rc_user_text'] = $options['onlyByUser'];
527 } elseif ( array_key_exists( 'notByUser', $options ) ) {
528 $conds[] = 'rc_user_text != ' . $db->addQuotes( $options['notByUser'] );
531 // Avoid brute force searches (T19342)
533 if ( !$user->isAllowed( 'deletedhistory' ) ) {
534 $bitmask = Revision
::DELETED_USER
;
535 } elseif ( !$user->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
536 $bitmask = Revision
::DELETED_USER | Revision
::DELETED_RESTRICTED
;
539 $conds[] = $db->bitAnd( 'rc_deleted', $bitmask ) . " != $bitmask";
545 private function getExtraDeletedPageLogEntryRelatedCond( IDatabase
$db, User
$user ) {
546 // LogPage::DELETED_ACTION hides the affected page, too. So hide those
547 // entirely from the watchlist, or someone could guess the title.
549 if ( !$user->isAllowed( 'deletedhistory' ) ) {
550 $bitmask = LogPage
::DELETED_ACTION
;
551 } elseif ( !$user->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
552 $bitmask = LogPage
::DELETED_ACTION | LogPage
::DELETED_RESTRICTED
;
555 return $db->makeList( [
556 'rc_type != ' . RC_LOG
,
557 $db->bitAnd( 'rc_deleted', $bitmask ) . " != $bitmask",
563 private function getStartFromConds( IDatabase
$db, array $options, array $startFrom ) {
564 $op = $options['dir'] === self
::DIR_OLDER ?
'<' : '>';
565 list( $rcTimestamp, $rcId ) = $startFrom;
566 $rcTimestamp = $db->addQuotes( $db->timestamp( $rcTimestamp ) );
568 return $db->makeList(
570 "rc_timestamp $op $rcTimestamp",
573 "rc_timestamp = $rcTimestamp",
583 private function getWatchedItemsForUserQueryConds( IDatabase
$db, User
$user, array $options ) {
584 $conds = [ 'wl_user' => $user->getId() ];
585 if ( $options['namespaceIds'] ) {
586 $conds['wl_namespace'] = array_map( 'intval', $options['namespaceIds'] );
588 if ( isset( $options['filter'] ) ) {
589 $filter = $options['filter'];
590 if ( $filter === self
::FILTER_CHANGED
) {
591 $conds[] = 'wl_notificationtimestamp IS NOT NULL';
593 $conds[] = 'wl_notificationtimestamp IS NULL';
597 if ( isset( $options['from'] ) ) {
598 $op = $options['sort'] === self
::SORT_ASC ?
'>' : '<';
599 $conds[] = $this->getFromUntilTargetConds( $db, $options['from'], $op );
601 if ( isset( $options['until'] ) ) {
602 $op = $options['sort'] === self
::SORT_ASC ?
'<' : '>';
603 $conds[] = $this->getFromUntilTargetConds( $db, $options['until'], $op );
605 if ( isset( $options['startFrom'] ) ) {
606 $op = $options['sort'] === self
::SORT_ASC ?
'>' : '<';
607 $conds[] = $this->getFromUntilTargetConds( $db, $options['startFrom'], $op );
614 * Creates a query condition part for getting only items before or after the given link target
615 * (while ordering using $sort mode)
617 * @param IDatabase $db
618 * @param LinkTarget $target
619 * @param string $op comparison operator to use in the conditions
622 private function getFromUntilTargetConds( IDatabase
$db, LinkTarget
$target, $op ) {
623 return $db->makeList(
625 "wl_namespace $op " . $target->getNamespace(),
628 'wl_namespace = ' . $target->getNamespace(),
629 "wl_title $op= " . $db->addQuotes( $target->getDBkey() )
638 private function getWatchedItemsWithRCInfoQueryDbOptions( array $options ) {
641 if ( array_key_exists( 'dir', $options ) ) {
642 $sort = $options['dir'] === self
::DIR_OLDER ?
' DESC' : '';
643 $dbOptions['ORDER BY'] = [ 'rc_timestamp' . $sort, 'rc_id' . $sort ];
646 if ( array_key_exists( 'limit', $options ) ) {
647 $dbOptions['LIMIT'] = (int)$options['limit'] +
1;
653 private function getWatchedItemsForUserQueryDbOptions( array $options ) {
655 if ( array_key_exists( 'sort', $options ) ) {
656 $dbOptions['ORDER BY'] = [
657 "wl_namespace {$options['sort']}",
658 "wl_title {$options['sort']}"
660 if ( count( $options['namespaceIds'] ) === 1 ) {
661 $dbOptions['ORDER BY'] = "wl_title {$options['sort']}";
664 if ( array_key_exists( 'limit', $options ) ) {
665 $dbOptions['LIMIT'] = (int)$options['limit'];
670 private function getWatchedItemsWithRCInfoQueryJoinConds( array $options ) {
672 'watchlist' => [ 'INNER JOIN',
674 'wl_namespace=rc_namespace',
679 if ( !$options['allRevisions'] ) {
680 $joinConds['page'] = [ 'LEFT JOIN', 'rc_cur_id=page_id' ];
682 if ( in_array( self
::INCLUDE_COMMENT
, $options['includeFields'] ) ) {
683 $joinConds +
= $this->commentStore
->getJoin( 'rc_comment' )['joins'];
685 if ( in_array( self
::INCLUDE_TAGS
, $options['includeFields'] ) ) {
686 $joinConds['tag_summary'] = [ 'LEFT JOIN', [ 'rc_id=ts_rc_id' ] ];