Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
98.72% covered (success)
98.72%
387 / 392
78.95% covered (warning)
78.95%
15 / 19
CRAP
0.00% covered (danger)
0.00%
0 / 1
WatchedItemQueryService
98.72% covered (success)
98.72%
387 / 392
78.95% covered (warning)
78.95%
15 / 19
131
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
 getExtensions
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 getWatchedItemsWithRecentChangeInfo
100.00% covered (success)
100.00%
92 / 92
100.00% covered (success)
100.00%
1 / 1
14
 getWatchedItemsForUser
100.00% covered (success)
100.00%
50 / 50
100.00% covered (success)
100.00%
1 / 1
9
 getRecentChangeFieldsFromRow
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
 getWatchedItemsWithRCInfoQueryTables
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
10
 getWatchedItemsWithRCInfoQueryFields
97.37% covered (success)
97.37%
37 / 38
0.00% covered (danger)
0.00%
0 / 1
12
 getWatchedItemsWithRCInfoQueryConds
100.00% covered (success)
100.00%
25 / 25
100.00% covered (success)
100.00%
1 / 1
9
 getWatchlistOwnerId
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
4
 getWatchedItemsWithRCInfoQueryFilterConds
94.12% covered (success)
94.12%
32 / 34
0.00% covered (danger)
0.00%
0 / 1
17.06
 getStartEndConds
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
7
 getUserRelatedConds
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
8
 getExtraDeletedPageLogEntryRelatedCond
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
4
 getStartFromConds
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
2
 getWatchedItemsForUserQueryConds
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
1 / 1
10
 getFromUntilTargetConds
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 getWatchedItemsWithRCInfoQueryDbOptions
88.89% covered (warning)
88.89%
8 / 9
0.00% covered (danger)
0.00%
0 / 1
5.03
 getWatchedItemsForUserQueryDbOptions
92.31% covered (success)
92.31%
12 / 13
0.00% covered (danger)
0.00%
0 / 1
5.01
 getWatchedItemsWithRCInfoQueryJoinConds
100.00% covered (success)
100.00%
21 / 21
100.00% covered (success)
100.00%
1 / 1
10
1<?php
2
3use MediaWiki\CommentStore\CommentStore;
4use MediaWiki\HookContainer\HookContainer;
5use MediaWiki\HookContainer\HookRunner;
6use MediaWiki\Linker\LinkTarget;
7use MediaWiki\Permissions\Authority;
8use MediaWiki\Revision\RevisionRecord;
9use MediaWiki\Title\TitleValue;
10use MediaWiki\User\Options\UserOptionsLookup;
11use MediaWiki\User\TempUser\TempUserConfig;
12use MediaWiki\User\User;
13use MediaWiki\User\UserIdentity;
14use Wikimedia\Assert\Assert;
15use Wikimedia\Rdbms\IConnectionProvider;
16use Wikimedia\Rdbms\IExpression;
17use Wikimedia\Rdbms\IReadableDatabase;
18
19/**
20 * Class performing complex database queries related to WatchedItems.
21 *
22 * @since 1.28
23 *
24 * @file
25 * @ingroup Watchlist
26 *
27 * @license GPL-2.0-or-later
28 */
29class WatchedItemQueryService {
30
31    public const DIR_OLDER = 'older';
32    public const DIR_NEWER = 'newer';
33
34    public const INCLUDE_FLAGS = 'flags';
35    public const INCLUDE_USER = 'user';
36    public const INCLUDE_USER_ID = 'userid';
37    public const INCLUDE_COMMENT = 'comment';
38    public const INCLUDE_PATROL_INFO = 'patrol';
39    public const INCLUDE_AUTOPATROL_INFO = 'autopatrol';
40    public const INCLUDE_SIZES = 'sizes';
41    public const INCLUDE_LOG_INFO = 'loginfo';
42    public const INCLUDE_TAGS = 'tags';
43
44    // FILTER_* constants are part of public API (are used in ApiQueryWatchlist and
45    // ApiQueryWatchlistRaw classes) and should not be changed.
46    // Changing values of those constants will result in a breaking change in the API
47    public const FILTER_MINOR = 'minor';
48    public const FILTER_NOT_MINOR = '!minor';
49    public const FILTER_BOT = 'bot';
50    public const FILTER_NOT_BOT = '!bot';
51    public const FILTER_ANON = 'anon';
52    public const FILTER_NOT_ANON = '!anon';
53    public const FILTER_PATROLLED = 'patrolled';
54    public const FILTER_NOT_PATROLLED = '!patrolled';
55    public const FILTER_AUTOPATROLLED = 'autopatrolled';
56    public const FILTER_NOT_AUTOPATROLLED = '!autopatrolled';
57    public const FILTER_UNREAD = 'unread';
58    public const FILTER_NOT_UNREAD = '!unread';
59    public const FILTER_CHANGED = 'changed';
60    public const FILTER_NOT_CHANGED = '!changed';
61
62    public const SORT_ASC = 'ASC';
63    public const SORT_DESC = 'DESC';
64
65    /**
66     * @var IConnectionProvider
67     */
68    private $dbProvider;
69
70    /** @var WatchedItemQueryServiceExtension[]|null */
71    private $extensions = null;
72
73    /** @var CommentStore */
74    private $commentStore;
75
76    /** @var WatchedItemStoreInterface */
77    private $watchedItemStore;
78
79    /** @var HookRunner */
80    private $hookRunner;
81
82    /** @var UserOptionsLookup */
83    private $userOptionsLookup;
84
85    /** @var TempUserConfig */
86    private $tempUserConfig;
87
88    /**
89     * @var bool Correlates to $wgWatchlistExpiry feature flag.
90     */
91    private $expiryEnabled;
92
93    /**
94     * @var int Max query execution time
95     */
96    private $maxQueryExecutionTime;
97
98    public function __construct(
99        IConnectionProvider $dbProvider,
100        CommentStore $commentStore,
101        WatchedItemStoreInterface $watchedItemStore,
102        HookContainer $hookContainer,
103        UserOptionsLookup $userOptionsLookup,
104        TempUserConfig $tempUserConfig,
105        bool $expiryEnabled = false,
106        int $maxQueryExecutionTime = 0
107    ) {
108        $this->dbProvider = $dbProvider;
109        $this->commentStore = $commentStore;
110        $this->watchedItemStore = $watchedItemStore;
111        $this->hookRunner = new HookRunner( $hookContainer );
112        $this->userOptionsLookup = $userOptionsLookup;
113        $this->tempUserConfig = $tempUserConfig;
114        $this->expiryEnabled = $expiryEnabled;
115        $this->maxQueryExecutionTime = $maxQueryExecutionTime;
116    }
117
118    /**
119     * @return WatchedItemQueryServiceExtension[]
120     */
121    private function getExtensions() {
122        if ( $this->extensions === null ) {
123            $this->extensions = [];
124            $this->hookRunner->onWatchedItemQueryServiceExtensions( $this->extensions, $this );
125        }
126        return $this->extensions;
127    }
128
129    /**
130     * @param User $user
131     * @param array $options Allowed keys:
132     *        'includeFields'       => string[] RecentChange fields to be included in the result,
133     *                                 self::INCLUDE_* constants should be used
134     *        'filters'             => string[] optional filters to narrow down resulted items
135     *        'namespaceIds'        => int[] optional namespace IDs to filter by
136     *                                 (defaults to all namespaces)
137     *        'allRevisions'        => bool return multiple revisions of the same page if true,
138     *                                 only the most recent if false (default)
139     *        'rcTypes'             => int[] which types of RecentChanges to include
140     *                                 (defaults to all types), allowed values: RC_EDIT, RC_NEW,
141     *                                 RC_LOG, RC_EXTERNAL, RC_CATEGORIZE
142     *        'onlyByUser'          => string only list changes by a specified user
143     *        'notByUser'           => string do not include changes by a specified user
144     *        'dir'                 => string in which direction to enumerate, accepted values:
145     *                                 - DIR_OLDER list newest first
146     *                                 - DIR_NEWER list oldest first
147     *        'start'               => string (format accepted by wfTimestamp) requires 'dir' option,
148     *                                 timestamp to start enumerating from
149     *        'end'                 => string (format accepted by wfTimestamp) requires 'dir' option,
150     *                                 timestamp to end enumerating
151     *        'watchlistOwner'      => UserIdentity user whose watchlist items should be listed if different
152     *                                 than the one specified with $user param, requires
153     *                                 'watchlistOwnerToken' option
154     *        'watchlistOwnerToken' => string a watchlist token used to access another user's
155     *                                 watchlist, used with 'watchlistOwnerToken' option
156     *        'limit'               => int maximum numbers of items to return
157     *        'usedInGenerator'     => bool include only RecentChange id field required by the
158     *                                 generator ('rc_cur_id' or 'rc_this_oldid') if true, or all
159     *                                 id fields ('rc_cur_id', 'rc_this_oldid', 'rc_last_oldid')
160     *                                 if false (default)
161     * @param array|null &$startFrom Continuation value: [ string $rcTimestamp, int $rcId ]
162     * @return array[] Array of pairs ( WatchedItem $watchedItem, string[] $recentChangeInfo ),
163     *         where $recentChangeInfo contains the following keys:
164     *         - 'rc_id',
165     *         - 'rc_namespace',
166     *         - 'rc_title',
167     *         - 'rc_timestamp',
168     *         - 'rc_type',
169     *         - 'rc_deleted',
170     *         Additional keys could be added by specifying the 'includeFields' option
171     */
172    public function getWatchedItemsWithRecentChangeInfo(
173        User $user, array $options = [], &$startFrom = null
174    ) {
175        $options += [
176            'includeFields' => [],
177            'namespaceIds' => [],
178            'filters' => [],
179            'allRevisions' => false,
180            'usedInGenerator' => false
181        ];
182
183        Assert::parameter(
184            !isset( $options['rcTypes'] )
185                || !array_diff( $options['rcTypes'], [ RC_EDIT, RC_NEW, RC_LOG, RC_EXTERNAL, RC_CATEGORIZE ] ),
186            '$options[\'rcTypes\']',
187            'must be an array containing only: RC_EDIT, RC_NEW, RC_LOG, RC_EXTERNAL and/or RC_CATEGORIZE'
188        );
189        Assert::parameter(
190            !isset( $options['dir'] ) || in_array( $options['dir'], [ self::DIR_OLDER, self::DIR_NEWER ] ),
191            '$options[\'dir\']',
192            'must be DIR_OLDER or DIR_NEWER'
193        );
194        Assert::parameter(
195            ( !isset( $options['start'] ) && !isset( $options['end'] ) && $startFrom === null )
196                || isset( $options['dir'] ),
197            '$options[\'dir\']',
198            'must be provided when providing the "start" or "end" options or the $startFrom parameter'
199        );
200        Assert::parameter(
201            !isset( $options['startFrom'] ),
202            '$options[\'startFrom\']',
203            'must not be provided, use $startFrom instead'
204        );
205        Assert::parameter(
206            !isset( $startFrom ) || ( is_array( $startFrom ) && count( $startFrom ) === 2 ),
207            '$startFrom',
208            'must be a two-element array'
209        );
210        if ( array_key_exists( 'watchlistOwner', $options ) ) {
211            Assert::parameterType(
212                UserIdentity::class,
213                $options['watchlistOwner'],
214                '$options[\'watchlistOwner\']'
215            );
216            Assert::parameter(
217                isset( $options['watchlistOwnerToken'] ),
218                '$options[\'watchlistOwnerToken\']',
219                'must be provided when providing watchlistOwner option'
220            );
221        }
222
223        $db = $this->dbProvider->getReplicaDatabase();
224
225        $tables = $this->getWatchedItemsWithRCInfoQueryTables( $options );
226        $fields = $this->getWatchedItemsWithRCInfoQueryFields( $options );
227        $conds = $this->getWatchedItemsWithRCInfoQueryConds( $db, $user, $options );
228        $dbOptions = $this->getWatchedItemsWithRCInfoQueryDbOptions( $options );
229        $joinConds = $this->getWatchedItemsWithRCInfoQueryJoinConds( $options );
230
231        if ( $startFrom !== null ) {
232            $conds[] = $this->getStartFromConds( $db, $options, $startFrom );
233        }
234