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( LoadBalancer
$loadBalancer ) {
63 $this->loadBalancer
= $loadBalancer;
64 $this->commentStore
= CommentStore
::getStore();
68 * @return WatchedItemQueryServiceExtension[]
70 private function getExtensions() {
71 if ( $this->extensions
=== null ) {
72 $this->extensions
= [];
73 Hooks
::run( 'WatchedItemQueryServiceExtensions', [ &$this->extensions
, $this ] );
75 return $this->extensions
;
82 private function getConnection() {
83 return $this->loadBalancer
->getConnectionRef( DB_REPLICA
, [ 'watchlist' ] );
88 * @param array $options Allowed keys:
89 * 'includeFields' => string[] RecentChange fields to be included in the result,
90 * self::INCLUDE_* constants should be used
91 * 'filters' => string[] optional filters to narrow down resulted items
92 * 'namespaceIds' => int[] optional namespace IDs to filter by
93 * (defaults to all namespaces)
94 * 'allRevisions' => bool return multiple revisions of the same page if true,
95 * only the most recent if false (default)
96 * 'rcTypes' => int[] which types of RecentChanges to include
97 * (defaults to all types), allowed values: RC_EDIT, RC_NEW,
98 * RC_LOG, RC_EXTERNAL, RC_CATEGORIZE
99 * 'onlyByUser' => string only list changes by a specified user
100 * 'notByUser' => string do not incluide changes by a specified user
101 * 'dir' => string in which direction to enumerate, accepted values:
102 * - DIR_OLDER list newest first
103 * - DIR_NEWER list oldest first
104 * 'start' => string (format accepted by wfTimestamp) requires 'dir' option,
105 * timestamp to start enumerating from
106 * 'end' => string (format accepted by wfTimestamp) requires 'dir' option,
107 * timestamp to end enumerating
108 * 'watchlistOwner' => User user whose watchlist items should be listed if different
109 * than the one specified with $user param,
110 * requires 'watchlistOwnerToken' option
111 * 'watchlistOwnerToken' => string a watchlist token used to access another user's
112 * watchlist, used with 'watchlistOwnerToken' option
113 * 'limit' => int maximum numbers of items to return
114 * 'usedInGenerator' => bool include only RecentChange id field required by the
115 * generator ('rc_cur_id' or 'rc_this_oldid') if true, or all
116 * id fields ('rc_cur_id', 'rc_this_oldid', 'rc_last_oldid')
118 * @param array|null &$startFrom Continuation value: [ string $rcTimestamp, int $rcId ]
119 * @return array of pairs ( WatchedItem $watchedItem, string[] $recentChangeInfo ),
120 * where $recentChangeInfo contains the following keys:
127 * Additional keys could be added by specifying the 'includeFields' option
129 public function getWatchedItemsWithRecentChangeInfo(
130 User
$user, array $options = [], &$startFrom = null
133 'includeFields' => [],
134 'namespaceIds' => [],
136 'allRevisions' => false,
137 'usedInGenerator' => false
141 !isset( $options['rcTypes'] )
142 ||
!array_diff( $options['rcTypes'], [ RC_EDIT
, RC_NEW
, RC_LOG
, RC_EXTERNAL
, RC_CATEGORIZE
] ),
143 '$options[\'rcTypes\']',
144 'must be an array containing only: RC_EDIT, RC_NEW, RC_LOG, RC_EXTERNAL and/or RC_CATEGORIZE'
147 !isset( $options['dir'] ) ||
in_array( $options['dir'], [ self
::DIR_OLDER
, self
::DIR_NEWER
] ),
149 'must be DIR_OLDER or DIR_NEWER'
152 !isset( $options['start'] ) && !isset( $options['end'] ) && $startFrom === null
153 ||
isset( $options['dir'] ),
155 'must be provided when providing the "start" or "end" options or the $startFrom parameter'
158 !isset( $options['startFrom'] ),
159 '$options[\'startFrom\']',
160 'must not be provided, use $startFrom instead'
163 !isset( $startFrom ) ||
( is_array( $startFrom ) && count( $startFrom ) === 2 ),
165 'must be a two-element array'
167 if ( array_key_exists( 'watchlistOwner', $options ) ) {
168 Assert
::parameterType(
170 $options['watchlistOwner'],
171 '$options[\'watchlistOwner\']'
174 isset( $options['watchlistOwnerToken'] ),
175 '$options[\'watchlistOwnerToken\']',
176 'must be provided when providing watchlistOwner option'
180 $db = $this->getConnection();
182 $tables = $this->getWatchedItemsWithRCInfoQueryTables( $options );
183 $fields = $this->getWatchedItemsWithRCInfoQueryFields( $options );
184 $conds = $this->getWatchedItemsWithRCInfoQueryConds( $db, $user, $options );
185 $dbOptions = $this->getWatchedItemsWithRCInfoQueryDbOptions( $options );
186 $joinConds = $this->getWatchedItemsWithRCInfoQueryJoinConds( $options );
188 if ( $startFrom !== null ) {
189 $conds[] = $this->getStartFromConds( $db, $options, $startFrom );
192 foreach ( $this->getExtensions() as $extension ) {
193 $extension->modifyWatchedItemsWithRCInfoQuery(
194 $user, $options, $db,
212 $limit = isset( $dbOptions['LIMIT'] ) ?
$dbOptions['LIMIT'] : INF
;
215 foreach ( $res as $row ) {
216 if ( --$limit <= 0 ) {
217 $startFrom = [ $row->rc_timestamp
, $row->rc_id
];
224 new TitleValue( (int)$row->rc_namespace
, $row->rc_title
),
225 $row->wl_notificationtimestamp
227 $this->getRecentChangeFieldsFromRow( $row )
231 foreach ( $this->getExtensions() as $extension ) {
232 $extension->modifyWatchedItemsWithRCInfo( $user, $options, $db, $items, $res, $startFrom );
239 * For simple listing of user's watchlist items, see WatchedItemStore::getWatchedItemsForUser
242 * @param array $options Allowed keys:
243 * 'sort' => string optional sorting by namespace ID and title
244 * one of the self::SORT_* constants
245 * 'namespaceIds' => int[] optional namespace IDs to filter by (defaults to all namespaces)
246 * 'limit' => int maximum number of items to return
247 * 'filter' => string optional filter, one of the self::FILTER_* contants
248 * 'from' => LinkTarget requires 'sort' key, only return items starting from
249 * those related to the link target
250 * 'until' => LinkTarget requires 'sort' key, only return items until
251 * those related to the link target
252 * 'startFrom' => LinkTarget requires 'sort' key, only return items starting from
253 * those related to the link target, allows to skip some link targets
254 * specified using the form option
255 * @return WatchedItem[]
257 public function getWatchedItemsForUser( User
$user, array $options = [] ) {
258 if ( $user->isAnon() ) {
259 // TODO: should this just return an empty array or rather complain loud at this point
260 // as e.g. ApiBase::getWatchlistUser does?
264 $options +
= [ 'namespaceIds' => [] ];
267 !isset( $options['sort'] ) ||
in_array( $options['sort'], [ self
::SORT_ASC
, self
::SORT_DESC
] ),
268 '$options[\'sort\']',
269 'must be SORT_ASC or SORT_DESC'
272 !isset( $options['filter'] ) ||
in_array(
273 $options['filter'], [ self
::FILTER_CHANGED
, self
::FILTER_NOT_CHANGED
]
275 '$options[\'filter\']',
276 'must be FILTER_CHANGED or FILTER_NOT_CHANGED'
279 !isset( $options['from'] ) && !isset( $options['until'] ) && !isset( $options['startFrom'] )
280 ||
isset( $options['sort'] ),
281 '$options[\'sort\']',
282 'must be provided if any of "from", "until", "startFrom" options is provided'
285 $db = $this->getConnection();
287 $conds = $this->getWatchedItemsForUserQueryConds( $db, $user, $options );
288 $dbOptions = $this->getWatchedItemsForUserQueryDbOptions( $options );
292 [ 'wl_namespace', 'wl_title', 'wl_notificationtimestamp' ],
299 foreach ( $res as $row ) {
300 // todo these could all be cached at some point?
301 $watchedItems[] = new WatchedItem(
303 new TitleValue( (int)$row->wl_namespace
, $row->wl_title
),
304 $row->wl_notificationtimestamp
308 return $watchedItems;
311 private function getRecentChangeFieldsFromRow( stdClass
$row ) {
312 // This can be simplified to single array_filter call filtering by key value,
313 // once we stop supporting PHP 5.5
314 $allFields = get_object_vars( $row );
315 $rcKeys = array_filter(
316 array_keys( $allFields ),
318 return substr( $key, 0, 3 ) === 'rc_';
321 return array_intersect_key( $allFields, array_flip( $rcKeys ) );
324 private function getWatchedItemsWithRCInfoQueryTables( array $options ) {
325 $tables = [ 'recentchanges', 'watchlist' ];
326 if ( !$options['allRevisions'] ) {
329 if ( in_array( self
::INCLUDE_COMMENT
, $options['includeFields'] ) ) {
330 $tables +
= $this->commentStore
->getJoin( 'rc_comment' )['tables'];
332 if ( in_array( self
::INCLUDE_TAGS
, $options['includeFields'] ) ) {
333 $tables[] = 'tag_summary';
338 private function getWatchedItemsWithRCInfoQueryFields( array $options ) {
346 'wl_notificationtimestamp'
354 if ( $options['usedInGenerator'] ) {
355 if ( $options['allRevisions'] ) {
356 $rcIdFields = [ 'rc_this_oldid' ];
358 $rcIdFields = [ 'rc_cur_id' ];
361 $fields = array_merge( $fields, $rcIdFields );
363 if ( in_array( self
::INCLUDE_FLAGS
, $options['includeFields'] ) ) {
364 $fields = array_merge( $fields, [ 'rc_type', 'rc_minor', 'rc_bot' ] );
366 if ( in_array( self
::INCLUDE_USER
, $options['includeFields'] ) ) {
367 $fields[] = 'rc_user_text';
369 if ( in_array( self
::INCLUDE_USER_ID
, $options['includeFields'] ) ) {
370 $fields[] = 'rc_user';
372 if ( in_array( self
::INCLUDE_COMMENT
, $options['includeFields'] ) ) {
373 $fields +
= $this->commentStore
->getJoin( 'rc_comment' )['fields'];
375 if ( in_array( self
::INCLUDE_PATROL_INFO
, $options['includeFields'] ) ) {
376 $fields = array_merge( $fields, [ 'rc_patrolled', 'rc_log_type' ] );
378 if ( in_array( self
::INCLUDE_SIZES
, $options['includeFields'] ) ) {
379 $fields = array_merge( $fields, [ 'rc_old_len', 'rc_new_len' ] );
381 if ( in_array( self
::INCLUDE_LOG_INFO
, $options['includeFields'] ) ) {
382 $fields = array_merge( $fields, [ 'rc_logid', 'rc_log_type', 'rc_log_action', 'rc_params' ] );
384 if ( in_array( self
::INCLUDE_TAGS
, $options['includeFields'] ) ) {
385 // prefixed with rc_ to include the field in getRecentChangeFieldsFromRow
386 $fields['rc_tags'] = 'ts_tags';
392 private function getWatchedItemsWithRCInfoQueryConds(
397 $watchlistOwnerId = $this->getWatchlistOwnerId( $user, $options );
398 $conds = [ 'wl_user' => $watchlistOwnerId ];
400 if ( !$options['allRevisions'] ) {
401 $conds[] = $db->makeList(
402 [ 'rc_this_oldid=page_latest', 'rc_type=' . RC_LOG
],
407 if ( $options['namespaceIds'] ) {
408 $conds['wl_namespace'] = array_map( 'intval', $options['namespaceIds'] );
411 if ( array_key_exists( 'rcTypes', $options ) ) {
412 $conds['rc_type'] = array_map( 'intval', $options['rcTypes'] );
415 $conds = array_merge(
417 $this->getWatchedItemsWithRCInfoQueryFilterConds( $user, $options )
420 $conds = array_merge( $conds, $this->getStartEndConds( $db, $options ) );
422 if ( !isset( $options['start'] ) && !isset( $options['end'] ) ) {
423 if ( $db->getType() === 'mysql' ) {
424 // This is an index optimization for mysql
425 $conds[] = 'rc_timestamp > ' . $db->addQuotes( '' );
429 $conds = array_merge( $conds, $this->getUserRelatedConds( $db, $user, $options ) );
431 $deletedPageLogCond = $this->getExtraDeletedPageLogEntryRelatedCond( $db, $user );
432 if ( $deletedPageLogCond ) {
433 $conds[] = $deletedPageLogCond;
439 private function getWatchlistOwnerId( User
$user, array $options ) {
440 if ( array_key_exists( 'watchlistOwner', $options ) ) {
441 /** @var User $watchlistOwner */
442 $watchlistOwner = $options['watchlistOwner'];
443 $ownersToken = $watchlistOwner->getOption( 'watchlisttoken' );
444 $token = $options['watchlistOwnerToken'];
445 if ( $ownersToken == '' ||
!hash_equals( $ownersToken, $token ) ) {
446 throw ApiUsageException
::newWithMessage( null, 'apierror-bad-watchlist-token', 'bad_wltoken' );
448 return $watchlistOwner->getId();
450 return $user->getId();
453 private function getWatchedItemsWithRCInfoQueryFilterConds( User
$user, array $options ) {
456 if ( in_array( self
::FILTER_MINOR
, $options['filters'] ) ) {
457 $conds[] = 'rc_minor != 0';
458 } elseif ( in_array( self
::FILTER_NOT_MINOR
, $options['filters'] ) ) {
459 $conds[] = 'rc_minor = 0';
462 if ( in_array( self
::FILTER_BOT
, $options['filters'] ) ) {
463 $conds[] = 'rc_bot != 0';
464 } elseif ( in_array( self
::FILTER_NOT_BOT
, $options['filters'] ) ) {
465 $conds[] = 'rc_bot = 0';
468 if ( in_array( self
::FILTER_ANON
, $options['filters'] ) ) {
469 $conds[] = 'rc_user = 0';
470 } elseif ( in_array( self
::FILTER_NOT_ANON
, $options['filters'] ) ) {
471 $conds[] = 'rc_user != 0';
474 if ( $user->useRCPatrol() ||
$user->useNPPatrol() ) {
475 // TODO: not sure if this should simply ignore patrolled filters if user does not have the patrol
476 // right, or maybe rather fail loud at this point, same as e.g. ApiQueryWatchlist does?
477 if ( in_array( self
::FILTER_PATROLLED
, $options['filters'] ) ) {
478 $conds[] = 'rc_patrolled != 0';
479 } elseif ( in_array( self
::FILTER_NOT_PATROLLED
, $options['filters'] ) ) {
480 $conds[] = 'rc_patrolled = 0';
484 if ( in_array( self
::FILTER_UNREAD
, $options['filters'] ) ) {
485 $conds[] = 'rc_timestamp >= wl_notificationtimestamp';
486 } elseif ( in_array( self
::FILTER_NOT_UNREAD
, $options['filters'] ) ) {
487 // TODO: should this be changed to use Database::makeList?
488 $conds[] = 'wl_notificationtimestamp IS NULL OR rc_timestamp < wl_notificationtimestamp';
494 private function getStartEndConds( IDatabase
$db, array $options ) {
495 if ( !isset( $options['start'] ) && !isset( $options['end'] ) ) {
501 if ( isset( $options['start'] ) ) {
502 $after = $options['dir'] === self
::DIR_OLDER ?
'<=' : '>=';
503 $conds[] = 'rc_timestamp ' . $after . ' ' .
504 $db->addQuotes( $db->timestamp( $options['start'] ) );
506 if ( isset( $options['end'] ) ) {
507 $before = $options['dir'] === self
::DIR_OLDER ?
'>=' : '<=';
508 $conds[] = 'rc_timestamp ' . $before . ' ' .
509 $db->addQuotes( $db->timestamp( $options['end'] ) );
515 private function getUserRelatedConds( IDatabase
$db, User
$user, array $options ) {
516 if ( !array_key_exists( 'onlyByUser', $options ) && !array_key_exists( 'notByUser', $options ) ) {
522 if ( array_key_exists( 'onlyByUser', $options ) ) {
523 $conds['rc_user_text'] = $options['onlyByUser'];
524 } elseif ( array_key_exists( 'notByUser', $options ) ) {
525 $conds[] = 'rc_user_text != ' . $db->addQuotes( $options['notByUser'] );
528 // Avoid brute force searches (T19342)
530 if ( !$user->isAllowed( 'deletedhistory' ) ) {
531 $bitmask = Revision
::DELETED_USER
;
532 } elseif ( !$user->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
533 $bitmask = Revision
::DELETED_USER | Revision
::DELETED_RESTRICTED
;
536 $conds[] = $db->bitAnd( 'rc_deleted', $bitmask ) . " != $bitmask";
542 private function getExtraDeletedPageLogEntryRelatedCond( IDatabase
$db, User
$user ) {
543 // LogPage::DELETED_ACTION hides the affected page, too. So hide those
544 // entirely from the watchlist, or someone could guess the title.
546 if ( !$user->isAllowed( 'deletedhistory' ) ) {
547 $bitmask = LogPage
::DELETED_ACTION
;
548 } elseif ( !$user->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
549 $bitmask = LogPage
::DELETED_ACTION | LogPage
::DELETED_RESTRICTED
;
552 return $db->makeList( [
553 'rc_type != ' . RC_LOG
,
554 $db->bitAnd( 'rc_deleted', $bitmask ) . " != $bitmask",
560 private function getStartFromConds( IDatabase
$db, array $options, array $startFrom ) {
561 $op = $options['dir'] === self
::DIR_OLDER ?
'<' : '>';
562 list( $rcTimestamp, $rcId ) = $startFrom;
563 $rcTimestamp = $db->addQuotes( $db->timestamp( $rcTimestamp ) );
565 return $db->makeList(
567 "rc_timestamp $op $rcTimestamp",
570 "rc_timestamp = $rcTimestamp",
580 private function getWatchedItemsForUserQueryConds( IDatabase
$db, User
$user, array $options ) {
581 $conds = [ 'wl_user' => $user->getId() ];
582 if ( $options['namespaceIds'] ) {
583 $conds['wl_namespace'] = array_map( 'intval', $options['namespaceIds'] );
585 if ( isset( $options['filter'] ) ) {
586 $filter = $options['filter'];
587 if ( $filter === self
::FILTER_CHANGED
) {
588 $conds[] = 'wl_notificationtimestamp IS NOT NULL';
590 $conds[] = 'wl_notificationtimestamp IS NULL';
594 if ( isset( $options['from'] ) ) {
595 $op = $options['sort'] === self
::SORT_ASC ?
'>' : '<';
596 $conds[] = $this->getFromUntilTargetConds( $db, $options['from'], $op );
598 if ( isset( $options['until'] ) ) {
599 $op = $options['sort'] === self
::SORT_ASC ?
'<' : '>';
600 $conds[] = $this->getFromUntilTargetConds( $db, $options['until'], $op );
602 if ( isset( $options['startFrom'] ) ) {
603 $op = $options['sort'] === self
::SORT_ASC ?
'>' : '<';
604 $conds[] = $this->getFromUntilTargetConds( $db, $options['startFrom'], $op );
611 * Creates a query condition part for getting only items before or after the given link target
612 * (while ordering using $sort mode)
614 * @param IDatabase $db
615 * @param LinkTarget $target
616 * @param string $op comparison operator to use in the conditions
619 private function getFromUntilTargetConds( IDatabase
$db, LinkTarget
$target, $op ) {
620 return $db->makeList(
622 "wl_namespace $op " . $target->getNamespace(),
625 'wl_namespace = ' . $target->getNamespace(),
626 "wl_title $op= " . $db->addQuotes( $target->getDBkey() )
635 private function getWatchedItemsWithRCInfoQueryDbOptions( array $options ) {
638 if ( array_key_exists( 'dir', $options ) ) {
639 $sort = $options['dir'] === self
::DIR_OLDER ?
' DESC' : '';
640 $dbOptions['ORDER BY'] = [ 'rc_timestamp' . $sort, 'rc_id' . $sort ];
643 if ( array_key_exists( 'limit', $options ) ) {
644 $dbOptions['LIMIT'] = (int)$options['limit'] +
1;
650 private function getWatchedItemsForUserQueryDbOptions( array $options ) {
652 if ( array_key_exists( 'sort', $options ) ) {
653 $dbOptions['ORDER BY'] = [
654 "wl_namespace {$options['sort']}",
655 "wl_title {$options['sort']}"
657 if ( count( $options['namespaceIds'] ) === 1 ) {
658 $dbOptions['ORDER BY'] = "wl_title {$options['sort']}";
661 if ( array_key_exists( 'limit', $options ) ) {
662 $dbOptions['LIMIT'] = (int)$options['limit'];
667 private function getWatchedItemsWithRCInfoQueryJoinConds( array $options ) {
669 'watchlist' => [ 'INNER JOIN',
671 'wl_namespace=rc_namespace',
676 if ( !$options['allRevisions'] ) {
677 $joinConds['page'] = [ 'LEFT JOIN', 'rc_cur_id=page_id' ];
679 if ( in_array( self
::INCLUDE_COMMENT
, $options['includeFields'] ) ) {
680 $joinConds +
= $this->commentStore
->getJoin( 'rc_comment' )['joins'];
682 if ( in_array( self
::INCLUDE_TAGS
, $options['includeFields'] ) ) {
683 $joinConds['tag_summary'] = [ 'LEFT JOIN', [ 'rc_id=ts_rc_id' ] ];