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 /** @var WatchedItemQueryServiceExtension[]|null */
54 private $extensions = null;
56 public function __construct( LoadBalancer
$loadBalancer ) {
57 $this->loadBalancer
= $loadBalancer;
61 * @return WatchedItemQueryServiceExtension[]
63 private function getExtensions() {
64 if ( $this->extensions
=== null ) {
65 $this->extensions
= [];
66 Hooks
::run( 'WatchedItemQueryServiceExtensions', [ &$this->extensions
, $this ] );
68 return $this->extensions
;
75 private function getConnection() {
76 return $this->loadBalancer
->getConnectionRef( DB_REPLICA
, [ 'watchlist' ] );
81 * @param array $options Allowed keys:
82 * 'includeFields' => string[] RecentChange fields to be included in the result,
83 * self::INCLUDE_* constants should be used
84 * 'filters' => string[] optional filters to narrow down resulted items
85 * 'namespaceIds' => int[] optional namespace IDs to filter by
86 * (defaults to all namespaces)
87 * 'allRevisions' => bool return multiple revisions of the same page if true,
88 * only the most recent if false (default)
89 * 'rcTypes' => int[] which types of RecentChanges to include
90 * (defaults to all types), allowed values: RC_EDIT, RC_NEW,
91 * RC_LOG, RC_EXTERNAL, RC_CATEGORIZE
92 * 'onlyByUser' => string only list changes by a specified user
93 * 'notByUser' => string do not incluide changes by a specified user
94 * 'dir' => string in which direction to enumerate, accepted values:
95 * - DIR_OLDER list newest first
96 * - DIR_NEWER list oldest first
97 * 'start' => string (format accepted by wfTimestamp) requires 'dir' option,
98 * timestamp to start enumerating from
99 * 'end' => string (format accepted by wfTimestamp) requires 'dir' option,
100 * timestamp to end enumerating
101 * 'watchlistOwner' => User user whose watchlist items should be listed if different
102 * than the one specified with $user param,
103 * requires 'watchlistOwnerToken' option
104 * 'watchlistOwnerToken' => string a watchlist token used to access another user's
105 * watchlist, used with 'watchlistOwnerToken' option
106 * 'limit' => int maximum numbers of items to return
107 * 'usedInGenerator' => bool include only RecentChange id field required by the
108 * generator ('rc_cur_id' or 'rc_this_oldid') if true, or all
109 * id fields ('rc_cur_id', 'rc_this_oldid', 'rc_last_oldid')
111 * @param array|null &$startFrom Continuation value: [ string $rcTimestamp, int $rcId ]
112 * @return array of pairs ( WatchedItem $watchedItem, string[] $recentChangeInfo ),
113 * where $recentChangeInfo contains the following keys:
120 * Additional keys could be added by specifying the 'includeFields' option
122 public function getWatchedItemsWithRecentChangeInfo(
123 User
$user, array $options = [], &$startFrom = null
126 'includeFields' => [],
127 'namespaceIds' => [],
129 'allRevisions' => false,
130 'usedInGenerator' => false
134 !isset( $options['rcTypes'] )
135 ||
!array_diff( $options['rcTypes'], [ RC_EDIT
, RC_NEW
, RC_LOG
, RC_EXTERNAL
, RC_CATEGORIZE
] ),
136 '$options[\'rcTypes\']',
137 'must be an array containing only: RC_EDIT, RC_NEW, RC_LOG, RC_EXTERNAL and/or RC_CATEGORIZE'
140 !isset( $options['dir'] ) ||
in_array( $options['dir'], [ self
::DIR_OLDER
, self
::DIR_NEWER
] ),
142 'must be DIR_OLDER or DIR_NEWER'
145 !isset( $options['start'] ) && !isset( $options['end'] ) && $startFrom === null
146 ||
isset( $options['dir'] ),
148 'must be provided when providing the "start" or "end" options or the $startFrom parameter'
151 !isset( $options['startFrom'] ),
152 '$options[\'startFrom\']',
153 'must not be provided, use $startFrom instead'
156 !isset( $startFrom ) ||
( is_array( $startFrom ) && count( $startFrom ) === 2 ),
158 'must be a two-element array'
160 if ( array_key_exists( 'watchlistOwner', $options ) ) {
161 Assert
::parameterType(
163 $options['watchlistOwner'],
164 '$options[\'watchlistOwner\']'
167 isset( $options['watchlistOwnerToken'] ),
168 '$options[\'watchlistOwnerToken\']',
169 'must be provided when providing watchlistOwner option'
173 $tables = [ 'recentchanges', 'watchlist' ];
174 if ( !$options['allRevisions'] ) {
178 $db = $this->getConnection();
180 $fields = $this->getWatchedItemsWithRCInfoQueryFields( $options );
181 $conds = $this->getWatchedItemsWithRCInfoQueryConds( $db, $user, $options );
182 $dbOptions = $this->getWatchedItemsWithRCInfoQueryDbOptions( $options );
183 $joinConds = $this->getWatchedItemsWithRCInfoQueryJoinConds( $options );
185 if ( $startFrom !== null ) {
186 $conds[] = $this->getStartFromConds( $db, $options, $startFrom );
189 foreach ( $this->getExtensions() as $extension ) {
190 $extension->modifyWatchedItemsWithRCInfoQuery(
191 $user, $options, $db,
209 $limit = isset( $dbOptions['LIMIT'] ) ?
$dbOptions['LIMIT'] : INF
;
212 foreach ( $res as $row ) {
213 if ( --$limit <= 0 ) {
214 $startFrom = [ $row->rc_timestamp
, $row->rc_id
];
221 new TitleValue( (int)$row->rc_namespace
, $row->rc_title
),
222 $row->wl_notificationtimestamp
224 $this->getRecentChangeFieldsFromRow( $row )
228 foreach ( $this->getExtensions() as $extension ) {
229 $extension->modifyWatchedItemsWithRCInfo( $user, $options, $db, $items, $res, $startFrom );
236 * For simple listing of user's watchlist items, see WatchedItemStore::getWatchedItemsForUser
239 * @param array $options Allowed keys:
240 * 'sort' => string optional sorting by namespace ID and title
241 * one of the self::SORT_* constants
242 * 'namespaceIds' => int[] optional namespace IDs to filter by (defaults to all namespaces)
243 * 'limit' => int maximum number of items to return
244 * 'filter' => string optional filter, one of the self::FILTER_* contants
245 * 'from' => LinkTarget requires 'sort' key, only return items starting from
246 * those related to the link target
247 * 'until' => LinkTarget requires 'sort' key, only return items until
248 * those related to the link target
249 * 'startFrom' => LinkTarget requires 'sort' key, only return items starting from
250 * those related to the link target, allows to skip some link targets
251 * specified using the form option
252 * @return WatchedItem[]
254 public function getWatchedItemsForUser( User
$user, array $options = [] ) {
255 if ( $user->isAnon() ) {
256 // TODO: should this just return an empty array or rather complain loud at this point
257 // as e.g. ApiBase::getWatchlistUser does?
261 $options +
= [ 'namespaceIds' => [] ];
264 !isset( $options['sort'] ) ||
in_array( $options['sort'], [ self
::SORT_ASC
, self
::SORT_DESC
] ),
265 '$options[\'sort\']',
266 'must be SORT_ASC or SORT_DESC'
269 !isset( $options['filter'] ) ||
in_array(
270 $options['filter'], [ self
::FILTER_CHANGED
, self
::FILTER_NOT_CHANGED
]
272 '$options[\'filter\']',
273 'must be FILTER_CHANGED or FILTER_NOT_CHANGED'
276 !isset( $options['from'] ) && !isset( $options['until'] ) && !isset( $options['startFrom'] )
277 ||
isset( $options['sort'] ),
278 '$options[\'sort\']',
279 'must be provided if any of "from", "until", "startFrom" options is provided'
282 $db = $this->getConnection();
284 $conds = $this->getWatchedItemsForUserQueryConds( $db, $user, $options );
285 $dbOptions = $this->getWatchedItemsForUserQueryDbOptions( $options );
289 [ 'wl_namespace', 'wl_title', 'wl_notificationtimestamp' ],
296 foreach ( $res as $row ) {
297 // todo these could all be cached at some point?
298 $watchedItems[] = new WatchedItem(
300 new TitleValue( (int)$row->wl_namespace
, $row->wl_title
),
301 $row->wl_notificationtimestamp
305 return $watchedItems;
308 private function getRecentChangeFieldsFromRow( stdClass
$row ) {
309 // This can be simplified to single array_filter call filtering by key value,
310 // once we stop supporting PHP 5.5
311 $allFields = get_object_vars( $row );
312 $rcKeys = array_filter(
313 array_keys( $allFields ),
315 return substr( $key, 0, 3 ) === 'rc_';
318 return array_intersect_key( $allFields, array_flip( $rcKeys ) );
321 private function getWatchedItemsWithRCInfoQueryFields( array $options ) {
329 'wl_notificationtimestamp'
337 if ( $options['usedInGenerator'] ) {
338 if ( $options['allRevisions'] ) {
339 $rcIdFields = [ 'rc_this_oldid' ];
341 $rcIdFields = [ 'rc_cur_id' ];
344 $fields = array_merge( $fields, $rcIdFields );
346 if ( in_array( self
::INCLUDE_FLAGS
, $options['includeFields'] ) ) {
347 $fields = array_merge( $fields, [ 'rc_type', 'rc_minor', 'rc_bot' ] );
349 if ( in_array( self
::INCLUDE_USER
, $options['includeFields'] ) ) {
350 $fields[] = 'rc_user_text';
352 if ( in_array( self
::INCLUDE_USER_ID
, $options['includeFields'] ) ) {
353 $fields[] = 'rc_user';
355 if ( in_array( self
::INCLUDE_COMMENT
, $options['includeFields'] ) ) {
356 $fields[] = 'rc_comment';
358 if ( in_array( self
::INCLUDE_PATROL_INFO
, $options['includeFields'] ) ) {
359 $fields = array_merge( $fields, [ 'rc_patrolled', 'rc_log_type' ] );
361 if ( in_array( self
::INCLUDE_SIZES
, $options['includeFields'] ) ) {
362 $fields = array_merge( $fields, [ 'rc_old_len', 'rc_new_len' ] );
364 if ( in_array( self
::INCLUDE_LOG_INFO
, $options['includeFields'] ) ) {
365 $fields = array_merge( $fields, [ 'rc_logid', 'rc_log_type', 'rc_log_action', 'rc_params' ] );
371 private function getWatchedItemsWithRCInfoQueryConds(
376 $watchlistOwnerId = $this->getWatchlistOwnerId( $user, $options );
377 $conds = [ 'wl_user' => $watchlistOwnerId ];
379 if ( !$options['allRevisions'] ) {
380 $conds[] = $db->makeList(
381 [ 'rc_this_oldid=page_latest', 'rc_type=' . RC_LOG
],
386 if ( $options['namespaceIds'] ) {
387 $conds['wl_namespace'] = array_map( 'intval', $options['namespaceIds'] );
390 if ( array_key_exists( 'rcTypes', $options ) ) {
391 $conds['rc_type'] = array_map( 'intval', $options['rcTypes'] );
394 $conds = array_merge(
396 $this->getWatchedItemsWithRCInfoQueryFilterConds( $user, $options )
399 $conds = array_merge( $conds, $this->getStartEndConds( $db, $options ) );
401 if ( !isset( $options['start'] ) && !isset( $options['end'] ) ) {
402 if ( $db->getType() === 'mysql' ) {
403 // This is an index optimization for mysql
404 $conds[] = "rc_timestamp > ''";
408 $conds = array_merge( $conds, $this->getUserRelatedConds( $db, $user, $options ) );
410 $deletedPageLogCond = $this->getExtraDeletedPageLogEntryRelatedCond( $db, $user );
411 if ( $deletedPageLogCond ) {
412 $conds[] = $deletedPageLogCond;
418 private function getWatchlistOwnerId( User
$user, array $options ) {
419 if ( array_key_exists( 'watchlistOwner', $options ) ) {
420 /** @var User $watchlistOwner */
421 $watchlistOwner = $options['watchlistOwner'];
422 $ownersToken = $watchlistOwner->getOption( 'watchlisttoken' );
423 $token = $options['watchlistOwnerToken'];
424 if ( $ownersToken == '' ||
!hash_equals( $ownersToken, $token ) ) {
425 throw ApiUsageException
::newWithMessage( null, 'apierror-bad-watchlist-token', 'bad_wltoken' );
427 return $watchlistOwner->getId();
429 return $user->getId();
432 private function getWatchedItemsWithRCInfoQueryFilterConds( User
$user, array $options ) {
435 if ( in_array( self
::FILTER_MINOR
, $options['filters'] ) ) {
436 $conds[] = 'rc_minor != 0';
437 } elseif ( in_array( self
::FILTER_NOT_MINOR
, $options['filters'] ) ) {
438 $conds[] = 'rc_minor = 0';
441 if ( in_array( self
::FILTER_BOT
, $options['filters'] ) ) {
442 $conds[] = 'rc_bot != 0';
443 } elseif ( in_array( self
::FILTER_NOT_BOT
, $options['filters'] ) ) {
444 $conds[] = 'rc_bot = 0';
447 if ( in_array( self
::FILTER_ANON
, $options['filters'] ) ) {
448 $conds[] = 'rc_user = 0';
449 } elseif ( in_array( self
::FILTER_NOT_ANON
, $options['filters'] ) ) {
450 $conds[] = 'rc_user != 0';
453 if ( $user->useRCPatrol() ||
$user->useNPPatrol() ) {
454 // TODO: not sure if this should simply ignore patrolled filters if user does not have the patrol
455 // right, or maybe rather fail loud at this point, same as e.g. ApiQueryWatchlist does?
456 if ( in_array( self
::FILTER_PATROLLED
, $options['filters'] ) ) {
457 $conds[] = 'rc_patrolled != 0';
458 } elseif ( in_array( self
::FILTER_NOT_PATROLLED
, $options['filters'] ) ) {
459 $conds[] = 'rc_patrolled = 0';
463 if ( in_array( self
::FILTER_UNREAD
, $options['filters'] ) ) {
464 $conds[] = 'rc_timestamp >= wl_notificationtimestamp';
465 } elseif ( in_array( self
::FILTER_NOT_UNREAD
, $options['filters'] ) ) {
466 // TODO: should this be changed to use Database::makeList?
467 $conds[] = 'wl_notificationtimestamp IS NULL OR rc_timestamp < wl_notificationtimestamp';
473 private function getStartEndConds( IDatabase
$db, array $options ) {
474 if ( !isset( $options['start'] ) && ! isset( $options['end'] ) ) {
480 if ( isset( $options['start'] ) ) {
481 $after = $options['dir'] === self
::DIR_OLDER ?
'<=' : '>=';
482 $conds[] = 'rc_timestamp ' . $after . ' ' .
483 $db->addQuotes( $db->timestamp( $options['start'] ) );
485 if ( isset( $options['end'] ) ) {
486 $before = $options['dir'] === self
::DIR_OLDER ?
'>=' : '<=';
487 $conds[] = 'rc_timestamp ' . $before . ' ' .
488 $db->addQuotes( $db->timestamp( $options['end'] ) );
494 private function getUserRelatedConds( IDatabase
$db, User
$user, array $options ) {
495 if ( !array_key_exists( 'onlyByUser', $options ) && !array_key_exists( 'notByUser', $options ) ) {
501 if ( array_key_exists( 'onlyByUser', $options ) ) {
502 $conds['rc_user_text'] = $options['onlyByUser'];
503 } elseif ( array_key_exists( 'notByUser', $options ) ) {
504 $conds[] = 'rc_user_text != ' . $db->addQuotes( $options['notByUser'] );
507 // Avoid brute force searches (bug 17342)
509 if ( !$user->isAllowed( 'deletedhistory' ) ) {
510 $bitmask = Revision
::DELETED_USER
;
511 } elseif ( !$user->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
512 $bitmask = Revision
::DELETED_USER | Revision
::DELETED_RESTRICTED
;
515 $conds[] = $db->bitAnd( 'rc_deleted', $bitmask ) . " != $bitmask";
521 private function getExtraDeletedPageLogEntryRelatedCond( IDatabase
$db, User
$user ) {
522 // LogPage::DELETED_ACTION hides the affected page, too. So hide those
523 // entirely from the watchlist, or someone could guess the title.
525 if ( !$user->isAllowed( 'deletedhistory' ) ) {
526 $bitmask = LogPage
::DELETED_ACTION
;
527 } elseif ( !$user->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
528 $bitmask = LogPage
::DELETED_ACTION | LogPage
::DELETED_RESTRICTED
;
531 return $db->makeList( [
532 'rc_type != ' . RC_LOG
,
533 $db->bitAnd( 'rc_deleted', $bitmask ) . " != $bitmask",
539 private function getStartFromConds( IDatabase
$db, array $options, array $startFrom ) {
540 $op = $options['dir'] === self
::DIR_OLDER ?
'<' : '>';
541 list( $rcTimestamp, $rcId ) = $startFrom;
542 $rcTimestamp = $db->addQuotes( $db->timestamp( $rcTimestamp ) );
544 return $db->makeList(
546 "rc_timestamp $op $rcTimestamp",
549 "rc_timestamp = $rcTimestamp",
559 private function getWatchedItemsForUserQueryConds( IDatabase
$db, User
$user, array $options ) {
560 $conds = [ 'wl_user' => $user->getId() ];
561 if ( $options['namespaceIds'] ) {
562 $conds['wl_namespace'] = array_map( 'intval', $options['namespaceIds'] );
564 if ( isset( $options['filter'] ) ) {
565 $filter = $options['filter'];
566 if ( $filter === self
::FILTER_CHANGED
) {
567 $conds[] = 'wl_notificationtimestamp IS NOT NULL';
569 $conds[] = 'wl_notificationtimestamp IS NULL';
573 if ( isset( $options['from'] ) ) {
574 $op = $options['sort'] === self
::SORT_ASC ?
'>' : '<';
575 $conds[] = $this->getFromUntilTargetConds( $db, $options['from'], $op );
577 if ( isset( $options['until'] ) ) {
578 $op = $options['sort'] === self
::SORT_ASC ?
'<' : '>';
579 $conds[] = $this->getFromUntilTargetConds( $db, $options['until'], $op );
581 if ( isset( $options['startFrom'] ) ) {
582 $op = $options['sort'] === self
::SORT_ASC ?
'>' : '<';
583 $conds[] = $this->getFromUntilTargetConds( $db, $options['startFrom'], $op );
590 * Creates a query condition part for getting only items before or after the given link target
591 * (while ordering using $sort mode)
593 * @param IDatabase $db
594 * @param LinkTarget $target
595 * @param string $op comparison operator to use in the conditions
598 private function getFromUntilTargetConds( IDatabase
$db, LinkTarget
$target, $op ) {
599 return $db->makeList(
601 "wl_namespace $op " . $target->getNamespace(),
604 'wl_namespace = ' . $target->getNamespace(),
605 "wl_title $op= " . $db->addQuotes( $target->getDBkey() )
614 private function getWatchedItemsWithRCInfoQueryDbOptions( array $options ) {
617 if ( array_key_exists( 'dir', $options ) ) {
618 $sort = $options['dir'] === self
::DIR_OLDER ?
' DESC' : '';
619 $dbOptions['ORDER BY'] = [ 'rc_timestamp' . $sort, 'rc_id' . $sort ];
622 if ( array_key_exists( 'limit', $options ) ) {
623 $dbOptions['LIMIT'] = (int)$options['limit'] +
1;
629 private function getWatchedItemsForUserQueryDbOptions( array $options ) {
631 if ( array_key_exists( 'sort', $options ) ) {
632 $dbOptions['ORDER BY'] = [
633 "wl_namespace {$options['sort']}",
634 "wl_title {$options['sort']}"
636 if ( count( $options['namespaceIds'] ) === 1 ) {
637 $dbOptions['ORDER BY'] = "wl_title {$options['sort']}";
640 if ( array_key_exists( 'limit', $options ) ) {
641 $dbOptions['LIMIT'] = (int)$options['limit'];
646 private function getWatchedItemsWithRCInfoQueryJoinConds( array $options ) {
648 'watchlist' => [ 'INNER JOIN',
650 'wl_namespace=rc_namespace',
655 if ( !$options['allRevisions'] ) {
656 $joinConds['page'] = [ 'LEFT JOIN', 'rc_cur_id=page_id' ];