rdbms: Avoid selectDB() call in LoadMonitor new connections
[mediawiki.git] / includes / WatchedItemQueryService.php
blob1fafb24dbe323bde5d8e22ba6af599691d184d17
1 <?php
3 use Wikimedia\Rdbms\IDatabase;
4 use MediaWiki\Linker\LinkTarget;
5 use Wikimedia\Assert\Assert;
6 use Wikimedia\Rdbms\LoadBalancer;
8 /**
9 * Class performing complex database queries related to WatchedItems.
11 * @since 1.28
13 * @file
14 * @ingroup Watchlist
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';
31 // FILTER_* constants are part of public API (are used in ApiQueryWatchlist and
32 // ApiQueryWatchlistRaw classes) and should not be changed.
33 // Changing values of those constants will result in a breaking change in the API
34 const FILTER_MINOR = 'minor';
35 const FILTER_NOT_MINOR = '!minor';
36 const FILTER_BOT = 'bot';
37 const FILTER_NOT_BOT = '!bot';
38 const FILTER_ANON = 'anon';
39 const FILTER_NOT_ANON = '!anon';
40 const FILTER_PATROLLED = 'patrolled';
41 const FILTER_NOT_PATROLLED = '!patrolled';
42 const FILTER_UNREAD = 'unread';
43 const FILTER_NOT_UNREAD = '!unread';
44 const FILTER_CHANGED = 'changed';
45 const FILTER_NOT_CHANGED = '!changed';
47 const SORT_ASC = 'ASC';
48 const SORT_DESC = 'DESC';
50 /**
51 * @var LoadBalancer
53 private $loadBalancer;
55 /** @var WatchedItemQueryServiceExtension[]|null */
56 private $extensions = null;
58 public function __construct( LoadBalancer $loadBalancer ) {
59 $this->loadBalancer = $loadBalancer;
62 /**
63 * @return WatchedItemQueryServiceExtension[]
65 private function getExtensions() {
66 if ( $this->extensions === null ) {
67 $this->extensions = [];
68 Hooks::run( 'WatchedItemQueryServiceExtensions', [ &$this->extensions, $this ] );
70 return $this->extensions;
73 /**
74 * @return IDatabase
75 * @throws MWException
77 private function getConnection() {
78 return $this->loadBalancer->getConnectionRef( DB_REPLICA, [ 'watchlist' ] );
81 /**
82 * @param User $user
83 * @param array $options Allowed keys:
84 * 'includeFields' => string[] RecentChange fields to be included in the result,
85 * self::INCLUDE_* constants should be used
86 * 'filters' => string[] optional filters to narrow down resulted items
87 * 'namespaceIds' => int[] optional namespace IDs to filter by
88 * (defaults to all namespaces)
89 * 'allRevisions' => bool return multiple revisions of the same page if true,
90 * only the most recent if false (default)
91 * 'rcTypes' => int[] which types of RecentChanges to include
92 * (defaults to all types), allowed values: RC_EDIT, RC_NEW,
93 * RC_LOG, RC_EXTERNAL, RC_CATEGORIZE
94 * 'onlyByUser' => string only list changes by a specified user
95 * 'notByUser' => string do not incluide changes by a specified user
96 * 'dir' => string in which direction to enumerate, accepted values:
97 * - DIR_OLDER list newest first
98 * - DIR_NEWER list oldest first
99 * 'start' => string (format accepted by wfTimestamp) requires 'dir' option,
100 * timestamp to start enumerating from
101 * 'end' => string (format accepted by wfTimestamp) requires 'dir' option,
102 * timestamp to end enumerating
103 * 'watchlistOwner' => User user whose watchlist items should be listed if different
104 * than the one specified with $user param,
105 * requires 'watchlistOwnerToken' option
106 * 'watchlistOwnerToken' => string a watchlist token used to access another user's
107 * watchlist, used with 'watchlistOwnerToken' option
108 * 'limit' => int maximum numbers of items to return
109 * 'usedInGenerator' => bool include only RecentChange id field required by the
110 * generator ('rc_cur_id' or 'rc_this_oldid') if true, or all
111 * id fields ('rc_cur_id', 'rc_this_oldid', 'rc_last_oldid')
112 * if false (default)
113 * @param array|null &$startFrom Continuation value: [ string $rcTimestamp, int $rcId ]
114 * @return array of pairs ( WatchedItem $watchedItem, string[] $recentChangeInfo ),
115 * where $recentChangeInfo contains the following keys:
116 * - 'rc_id',
117 * - 'rc_namespace',
118 * - 'rc_title',
119 * - 'rc_timestamp',
120 * - 'rc_type',
121 * - 'rc_deleted',
122 * Additional keys could be added by specifying the 'includeFields' option
124 public function getWatchedItemsWithRecentChangeInfo(
125 User $user, array $options = [], &$startFrom = null
127 $options += [
128 'includeFields' => [],
129 'namespaceIds' => [],
130 'filters' => [],
131 'allRevisions' => false,
132 'usedInGenerator' => false
135 Assert::parameter(
136 !isset( $options['rcTypes'] )
137 || !array_diff( $options['rcTypes'], [ RC_EDIT, RC_NEW, RC_LOG, RC_EXTERNAL, RC_CATEGORIZE ] ),
138 '$options[\'rcTypes\']',
139 'must be an array containing only: RC_EDIT, RC_NEW, RC_LOG, RC_EXTERNAL and/or RC_CATEGORIZE'
141 Assert::parameter(
142 !isset( $options['dir'] ) || in_array( $options['dir'], [ self::DIR_OLDER, self::DIR_NEWER ] ),
143 '$options[\'dir\']',
144 'must be DIR_OLDER or DIR_NEWER'
146 Assert::parameter(
147 !isset( $options['start'] ) && !isset( $options['end'] ) && $startFrom === null
148 || isset( $options['dir'] ),
149 '$options[\'dir\']',
150 'must be provided when providing the "start" or "end" options or the $startFrom parameter'
152 Assert::parameter(
153 !isset( $options['startFrom'] ),
154 '$options[\'startFrom\']',
155 'must not be provided, use $startFrom instead'
157 Assert::parameter(
158 !isset( $startFrom ) || ( is_array( $startFrom ) && count( $startFrom ) === 2 ),
159 '$startFrom',
160 'must be a two-element array'
162 if ( array_key_exists( 'watchlistOwner', $options ) ) {
163 Assert::parameterType(
164 User::class,
165 $options['watchlistOwner'],
166 '$options[\'watchlistOwner\']'
168 Assert::parameter(
169 isset( $options['watchlistOwnerToken'] ),
170 '$options[\'watchlistOwnerToken\']',
171 'must be provided when providing watchlistOwner option'
175 $tables = [ 'recentchanges', 'watchlist' ];
176 if ( !$options['allRevisions'] ) {
177 $tables[] = 'page';
180 $db = $this->getConnection();
182 $fields = $this->getWatchedItemsWithRCInfoQueryFields( $options );
183 $conds = $this->getWatchedItemsWithRCInfoQueryConds( $db, $user, $options );
184 $dbOptions = $this->getWatchedItemsWithRCInfoQueryDbOptions( $options );
185 $joinConds = $this->getWatchedItemsWithRCInfoQueryJoinConds( $options );
187 if ( $startFrom !== null ) {
188 $conds[] = $this->getStartFromConds( $db, $options, $startFrom );
191 foreach ( $this->getExtensions() as $extension ) {
192 $extension->modifyWatchedItemsWithRCInfoQuery(
193 $user, $options, $db,
194 $tables,
195 $fields,
196 $conds,
197 $dbOptions,
198 $joinConds
202 $res = $db->select(
203 $tables,
204 $fields,
205 $conds,
206 __METHOD__,
207 $dbOptions,
208 $joinConds
211 $limit = isset( $dbOptions['LIMIT'] ) ? $dbOptions['LIMIT'] : INF;
212 $items = [];
213 $startFrom = null;
214 foreach ( $res as $row ) {
215 if ( --$limit <= 0 ) {
216 $startFrom = [ $row->rc_timestamp, $row->rc_id ];
217 break;
220 $items[] = [
221 new WatchedItem(
222 $user,
223 new TitleValue( (int)$row->rc_namespace, $row->rc_title ),
224 $row->wl_notificationtimestamp
226 $this->getRecentChangeFieldsFromRow( $row )
230 foreach ( $this->getExtensions() as $extension ) {
231 $extension->modifyWatchedItemsWithRCInfo( $user, $options, $db, $items, $res, $startFrom );
234 return $items;
238 * For simple listing of user's watchlist items, see WatchedItemStore::getWatchedItemsForUser
240 * @param User $user
241 * @param array $options Allowed keys:
242 * 'sort' => string optional sorting by namespace ID and title
243 * one of the self::SORT_* constants
244 * 'namespaceIds' => int[] optional namespace IDs to filter by (defaults to all namespaces)
245 * 'limit' => int maximum number of items to return
246 * 'filter' => string optional filter, one of the self::FILTER_* contants
247 * 'from' => LinkTarget requires 'sort' key, only return items starting from
248 * those related to the link target
249 * 'until' => LinkTarget requires 'sort' key, only return items until
250 * those related to the link target
251 * 'startFrom' => LinkTarget requires 'sort' key, only return items starting from
252 * those related to the link target, allows to skip some link targets
253 * specified using the form option
254 * @return WatchedItem[]
256 public function getWatchedItemsForUser( User $user, array $options = [] ) {
257 if ( $user->isAnon() ) {
258 // TODO: should this just return an empty array or rather complain loud at this point
259 // as e.g. ApiBase::getWatchlistUser does?
260 return [];
263 $options += [ 'namespaceIds' => [] ];
265 Assert::parameter(
266 !isset( $options['sort'] ) || in_array( $options['sort'], [ self::SORT_ASC, self::SORT_DESC ] ),
267 '$options[\'sort\']',
268 'must be SORT_ASC or SORT_DESC'
270 Assert::parameter(
271 !isset( $options['filter'] ) || in_array(
272 $options['filter'], [ self::FILTER_CHANGED, self::FILTER_NOT_CHANGED ]
274 '$options[\'filter\']',
275 'must be FILTER_CHANGED or FILTER_NOT_CHANGED'
277 Assert::parameter(
278 !isset( $options['from'] ) && !isset( $options['until'] ) && !isset( $options['startFrom'] )
279 || isset( $options['sort'] ),
280 '$options[\'sort\']',
281 'must be provided if any of "from", "until", "startFrom" options is provided'
284 $db = $this->getConnection();
286 $conds = $this->getWatchedItemsForUserQueryConds( $db, $user, $options );
287 $dbOptions = $this->getWatchedItemsForUserQueryDbOptions( $options );
289 $res = $db->select(
290 'watchlist',
291 [ 'wl_namespace', 'wl_title', 'wl_notificationtimestamp' ],
292 $conds,
293 __METHOD__,
294 $dbOptions
297 $watchedItems = [];
298 foreach ( $res as $row ) {
299 // todo these could all be cached at some point?
300 $watchedItems[] = new WatchedItem(
301 $user,
302 new TitleValue( (int)$row->wl_namespace, $row->wl_title ),
303 $row->wl_notificationtimestamp
307 return $watchedItems;
310 private function getRecentChangeFieldsFromRow( stdClass $row ) {
311 // This can be simplified to single array_filter call filtering by key value,
312 // once we stop supporting PHP 5.5
313 $allFields = get_object_vars( $row );
314 $rcKeys = array_filter(
315 array_keys( $allFields ),
316 function ( $key ) {
317 return substr( $key, 0, 3 ) === 'rc_';
320 return array_intersect_key( $allFields, array_flip( $rcKeys ) );
323 private function getWatchedItemsWithRCInfoQueryFields( array $options ) {
324 $fields = [
325 'rc_id',
326 'rc_namespace',
327 'rc_title',
328 'rc_timestamp',
329 'rc_type',
330 'rc_deleted',
331 'wl_notificationtimestamp'
334 $rcIdFields = [
335 'rc_cur_id',
336 'rc_this_oldid',
337 'rc_last_oldid',
339 if ( $options['usedInGenerator'] ) {
340 if ( $options['allRevisions'] ) {
341 $rcIdFields = [ 'rc_this_oldid' ];
342 } else {
343 $rcIdFields = [ 'rc_cur_id' ];
346 $fields = array_merge( $fields, $rcIdFields );
348 if ( in_array( self::INCLUDE_FLAGS, $options['includeFields'] ) ) {
349 $fields = array_merge( $fields, [ 'rc_type', 'rc_minor', 'rc_bot' ] );
351 if ( in_array( self::INCLUDE_USER, $options['includeFields'] ) ) {
352 $fields[] = 'rc_user_text';
354 if ( in_array( self::INCLUDE_USER_ID, $options['includeFields'] ) ) {
355 $fields[] = 'rc_user';
357 if ( in_array( self::INCLUDE_COMMENT, $options['includeFields'] ) ) {
358 $fields[] = 'rc_comment';
360 if ( in_array( self::INCLUDE_PATROL_INFO, $options['includeFields'] ) ) {
361 $fields = array_merge( $fields, [ 'rc_patrolled', 'rc_log_type' ] );
363 if ( in_array( self::INCLUDE_SIZES, $options['includeFields'] ) ) {
364 $fields = array_merge( $fields, [ 'rc_old_len', 'rc_new_len' ] );
366 if ( in_array( self::INCLUDE_LOG_INFO, $options['includeFields'] ) ) {
367 $fields = array_merge( $fields, [ 'rc_logid', 'rc_log_type', 'rc_log_action', 'rc_params' ] );
370 return $fields;
373 private function getWatchedItemsWithRCInfoQueryConds(
374 IDatabase $db,
375 User $user,
376 array $options
378 $watchlistOwnerId = $this->getWatchlistOwnerId( $user, $options );
379 $conds = [ 'wl_user' => $watchlistOwnerId ];
381 if ( !$options['allRevisions'] ) {
382 $conds[] = $db->makeList(
383 [ 'rc_this_oldid=page_latest', 'rc_type=' . RC_LOG ],
384 LIST_OR
388 if ( $options['namespaceIds'] ) {
389 $conds['wl_namespace'] = array_map( 'intval', $options['namespaceIds'] );
392 if ( array_key_exists( 'rcTypes', $options ) ) {
393 $conds['rc_type'] = array_map( 'intval', $options['rcTypes'] );
396 $conds = array_merge(
397 $conds,
398 $this->getWatchedItemsWithRCInfoQueryFilterConds( $user, $options )
401 $conds = array_merge( $conds, $this->getStartEndConds( $db, $options ) );
403 if ( !isset( $options['start'] ) && !isset( $options['end'] ) ) {
404 if ( $db->getType() === 'mysql' ) {
405 // This is an index optimization for mysql
406 $conds[] = 'rc_timestamp > ' . $db->addQuotes( '' );
410 $conds = array_merge( $conds, $this->getUserRelatedConds( $db, $user, $options ) );
412 $deletedPageLogCond = $this->getExtraDeletedPageLogEntryRelatedCond( $db, $user );
413 if ( $deletedPageLogCond ) {
414 $conds[] = $deletedPageLogCond;
417 return $conds;
420 private function getWatchlistOwnerId( User $user, array $options ) {
421 if ( array_key_exists( 'watchlistOwner', $options ) ) {
422 /** @var User $watchlistOwner */
423 $watchlistOwner = $options['watchlistOwner'];
424 $ownersToken = $watchlistOwner->getOption( 'watchlisttoken' );
425 $token = $options['watchlistOwnerToken'];
426 if ( $ownersToken == '' || !hash_equals( $ownersToken, $token ) ) {
427 throw ApiUsageException::newWithMessage( null, 'apierror-bad-watchlist-token', 'bad_wltoken' );
429 return $watchlistOwner->getId();
431 return $user->getId();
434 private function getWatchedItemsWithRCInfoQueryFilterConds( User $user, array $options ) {
435 $conds = [];
437 if ( in_array( self::FILTER_MINOR, $options['filters'] ) ) {
438 $conds[] = 'rc_minor != 0';
439 } elseif ( in_array( self::FILTER_NOT_MINOR, $options['filters'] ) ) {
440 $conds[] = 'rc_minor = 0';
443 if ( in_array( self::FILTER_BOT, $options['filters'] ) ) {
444 $conds[] = 'rc_bot != 0';
445 } elseif ( in_array( self::FILTER_NOT_BOT, $options['filters'] ) ) {
446 $conds[] = 'rc_bot = 0';
449 if ( in_array( self::FILTER_ANON, $options['filters'] ) ) {
450 $conds[] = 'rc_user = 0';
451 } elseif ( in_array( self::FILTER_NOT_ANON, $options['filters'] ) ) {
452 $conds[] = 'rc_user != 0';
455 if ( $user->useRCPatrol() || $user->useNPPatrol() ) {
456 // TODO: not sure if this should simply ignore patrolled filters if user does not have the patrol
457 // right, or maybe rather fail loud at this point, same as e.g. ApiQueryWatchlist does?
458 if ( in_array( self::FILTER_PATROLLED, $options['filters'] ) ) {
459 $conds[] = 'rc_patrolled != 0';
460 } elseif ( in_array( self::FILTER_NOT_PATROLLED, $options['filters'] ) ) {
461 $conds[] = 'rc_patrolled = 0';
465 if ( in_array( self::FILTER_UNREAD, $options['filters'] ) ) {
466 $conds[] = 'rc_timestamp >= wl_notificationtimestamp';
467 } elseif ( in_array( self::FILTER_NOT_UNREAD, $options['filters'] ) ) {
468 // TODO: should this be changed to use Database::makeList?
469 $conds[] = 'wl_notificationtimestamp IS NULL OR rc_timestamp < wl_notificationtimestamp';
472 return $conds;
475 private function getStartEndConds( IDatabase $db, array $options ) {
476 if ( !isset( $options['start'] ) && !isset( $options['end'] ) ) {
477 return [];
480 $conds = [];
482 if ( isset( $options['start'] ) ) {
483 $after = $options['dir'] === self::DIR_OLDER ? '<=' : '>=';
484 $conds[] = 'rc_timestamp ' . $after . ' ' .
485 $db->addQuotes( $db->timestamp( $options['start'] ) );
487 if ( isset( $options['end'] ) ) {
488 $before = $options['dir'] === self::DIR_OLDER ? '>=' : '<=';
489 $conds[] = 'rc_timestamp ' . $before . ' ' .
490 $db->addQuotes( $db->timestamp( $options['end'] ) );
493 return $conds;
496 private function getUserRelatedConds( IDatabase $db, User $user, array $options ) {
497 if ( !array_key_exists( 'onlyByUser', $options ) && !array_key_exists( 'notByUser', $options ) ) {
498 return [];
501 $conds = [];
503 if ( array_key_exists( 'onlyByUser', $options ) ) {
504 $conds['rc_user_text'] = $options['onlyByUser'];
505 } elseif ( array_key_exists( 'notByUser', $options ) ) {
506 $conds[] = 'rc_user_text != ' . $db->addQuotes( $options['notByUser'] );
509 // Avoid brute force searches (T19342)
510 $bitmask = 0;
511 if ( !$user->isAllowed( 'deletedhistory' ) ) {
512 $bitmask = Revision::DELETED_USER;
513 } elseif ( !$user->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
514 $bitmask = Revision::DELETED_USER | Revision::DELETED_RESTRICTED;
516 if ( $bitmask ) {
517 $conds[] = $db->bitAnd( 'rc_deleted', $bitmask ) . " != $bitmask";
520 return $conds;
523 private function getExtraDeletedPageLogEntryRelatedCond( IDatabase $db, User $user ) {
524 // LogPage::DELETED_ACTION hides the affected page, too. So hide those
525 // entirely from the watchlist, or someone could guess the title.
526 $bitmask = 0;
527 if ( !$user->isAllowed( 'deletedhistory' ) ) {
528 $bitmask = LogPage::DELETED_ACTION;
529 } elseif ( !$user->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
530 $bitmask = LogPage::DELETED_ACTION | LogPage::DELETED_RESTRICTED;
532 if ( $bitmask ) {
533 return $db->makeList( [
534 'rc_type != ' . RC_LOG,
535 $db->bitAnd( 'rc_deleted', $bitmask ) . " != $bitmask",
536 ], LIST_OR );
538 return '';
541 private function getStartFromConds( IDatabase $db, array $options, array $startFrom ) {
542 $op = $options['dir'] === self::DIR_OLDER ? '<' : '>';
543 list( $rcTimestamp, $rcId ) = $startFrom;
544 $rcTimestamp = $db->addQuotes( $db->timestamp( $rcTimestamp ) );
545 $rcId = (int)$rcId;
546 return $db->makeList(
548 "rc_timestamp $op $rcTimestamp",
549 $db->makeList(
551 "rc_timestamp = $rcTimestamp",
552 "rc_id $op= $rcId"
554 LIST_AND
557 LIST_OR
561 private function getWatchedItemsForUserQueryConds( IDatabase $db, User $user, array $options ) {
562 $conds = [ 'wl_user' => $user->getId() ];
563 if ( $options['namespaceIds'] ) {
564 $conds['wl_namespace'] = array_map( 'intval', $options['namespaceIds'] );
566 if ( isset( $options['filter'] ) ) {
567 $filter = $options['filter'];
568 if ( $filter === self::FILTER_CHANGED ) {
569 $conds[] = 'wl_notificationtimestamp IS NOT NULL';
570 } else {
571 $conds[] = 'wl_notificationtimestamp IS NULL';
575 if ( isset( $options['from'] ) ) {
576 $op = $options['sort'] === self::SORT_ASC ? '>' : '<';
577 $conds[] = $this->getFromUntilTargetConds( $db, $options['from'], $op );
579 if ( isset( $options['until'] ) ) {
580 $op = $options['sort'] === self::SORT_ASC ? '<' : '>';
581 $conds[] = $this->getFromUntilTargetConds( $db, $options['until'], $op );
583 if ( isset( $options['startFrom'] ) ) {
584 $op = $options['sort'] === self::SORT_ASC ? '>' : '<';
585 $conds[] = $this->getFromUntilTargetConds( $db, $options['startFrom'], $op );
588 return $conds;
592 * Creates a query condition part for getting only items before or after the given link target
593 * (while ordering using $sort mode)
595 * @param IDatabase $db
596 * @param LinkTarget $target
597 * @param string $op comparison operator to use in the conditions
598 * @return string
600 private function getFromUntilTargetConds( IDatabase $db, LinkTarget $target, $op ) {
601 return $db->makeList(
603 "wl_namespace $op " . $target->getNamespace(),
604 $db->makeList(
606 'wl_namespace = ' . $target->getNamespace(),
607 "wl_title $op= " . $db->addQuotes( $target->getDBkey() )
609 LIST_AND
612 LIST_OR
616 private function getWatchedItemsWithRCInfoQueryDbOptions( array $options ) {
617 $dbOptions = [];
619 if ( array_key_exists( 'dir', $options ) ) {
620 $sort = $options['dir'] === self::DIR_OLDER ? ' DESC' : '';
621 $dbOptions['ORDER BY'] = [ 'rc_timestamp' . $sort, 'rc_id' . $sort ];
624 if ( array_key_exists( 'limit', $options ) ) {
625 $dbOptions['LIMIT'] = (int)$options['limit'] + 1;
628 return $dbOptions;
631 private function getWatchedItemsForUserQueryDbOptions( array $options ) {
632 $dbOptions = [];
633 if ( array_key_exists( 'sort', $options ) ) {
634 $dbOptions['ORDER BY'] = [
635 "wl_namespace {$options['sort']}",
636 "wl_title {$options['sort']}"
638 if ( count( $options['namespaceIds'] ) === 1 ) {
639 $dbOptions['ORDER BY'] = "wl_title {$options['sort']}";
642 if ( array_key_exists( 'limit', $options ) ) {
643 $dbOptions['LIMIT'] = (int)$options['limit'];
645 return $dbOptions;
648 private function getWatchedItemsWithRCInfoQueryJoinConds( array $options ) {
649 $joinConds = [
650 'watchlist' => [ 'INNER JOIN',
652 'wl_namespace=rc_namespace',
653 'wl_title=rc_title'
657 if ( !$options['allRevisions'] ) {
658 $joinConds['page'] = [ 'LEFT JOIN', 'rc_cur_id=page_id' ];
660 return $joinConds;