Merge "Add .pipeline/ with dev image variant"
[lhc/web/wiklou.git] / includes / watcheditem / WatchedItemQueryService.php
1 <?php
2
3 use MediaWiki\Linker\LinkTarget;
4 use MediaWiki\Permissions\PermissionManager;
5 use MediaWiki\Revision\RevisionRecord;
6 use MediaWiki\User\UserIdentity;
7 use Wikimedia\Assert\Assert;
8 use Wikimedia\Rdbms\IDatabase;
9 use Wikimedia\Rdbms\ILoadBalancer;
10
11 /**
12 * Class performing complex database queries related to WatchedItems.
13 *
14 * @since 1.28
15 *
16 * @file
17 * @ingroup Watchlist
18 *
19 * @license GPL-2.0-or-later
20 */
21 class WatchedItemQueryService {
22
23 const DIR_OLDER = 'older';
24 const DIR_NEWER = 'newer';
25
26 const INCLUDE_FLAGS = 'flags';
27 const INCLUDE_USER = 'user';
28 const INCLUDE_USER_ID = 'userid';
29 const INCLUDE_COMMENT = 'comment';
30 const INCLUDE_PATROL_INFO = 'patrol';
31 const INCLUDE_AUTOPATROL_INFO = 'autopatrol';
32 const INCLUDE_SIZES = 'sizes';
33 const INCLUDE_LOG_INFO = 'loginfo';
34 const INCLUDE_TAGS = 'tags';
35
36 // FILTER_* constants are part of public API (are used in ApiQueryWatchlist and
37 // ApiQueryWatchlistRaw classes) and should not be changed.
38 // Changing values of those constants will result in a breaking change in the API
39 const FILTER_MINOR = 'minor';
40 const FILTER_NOT_MINOR = '!minor';
41 const FILTER_BOT = 'bot';
42 const FILTER_NOT_BOT = '!bot';
43 const FILTER_ANON = 'anon';
44 const FILTER_NOT_ANON = '!anon';
45 const FILTER_PATROLLED = 'patrolled';
46 const FILTER_NOT_PATROLLED = '!patrolled';
47 const FILTER_AUTOPATROLLED = 'autopatrolled';
48 const FILTER_NOT_AUTOPATROLLED = '!autopatrolled';
49 const FILTER_UNREAD = 'unread';
50 const FILTER_NOT_UNREAD = '!unread';
51 const FILTER_CHANGED = 'changed';
52 const FILTER_NOT_CHANGED = '!changed';
53
54 const SORT_ASC = 'ASC';
55 const SORT_DESC = 'DESC';
56
57 /**
58 * @var ILoadBalancer
59 */
60 private $loadBalancer;
61
62 /** @var WatchedItemQueryServiceExtension[]|null */
63 private $extensions = null;
64
65 /** @var CommentStore */
66 private $commentStore;
67
68 /** @var ActorMigration */
69 private $actorMigration;
70
71 /** @var WatchedItemStoreInterface */
72 private $watchedItemStore;
73
74 /** @var PermissionManager */
75 private $permissionManager;
76
77 public function __construct(
78 ILoadBalancer $loadBalancer,
79 CommentStore $commentStore,
80 ActorMigration $actorMigration,
81 WatchedItemStoreInterface $watchedItemStore,
82 PermissionManager $permissionManager
83 ) {
84 $this->loadBalancer = $loadBalancer;
85 $this->commentStore = $commentStore;
86 $this->actorMigration = $actorMigration;
87 $this->watchedItemStore = $watchedItemStore;
88 $this->permissionManager = $permissionManager;
89 }
90
91 /**
92 * @return WatchedItemQueryServiceExtension[]
93 */
94 private function getExtensions() {
95 if ( $this->extensions === null ) {
96 $this->extensions = [];
97 Hooks::run( 'WatchedItemQueryServiceExtensions', [ &$this->extensions, $this ] );
98 }
99 return $this->extensions;
100 }
101
102 /**
103 * @return IDatabase
104 */
105 private function getConnection() {
106 return $this->loadBalancer->getConnectionRef( DB_REPLICA, [ 'watchlist' ] );
107 }
108
109 /**
110 * @param User $user
111 * @param array $options Allowed keys:
112 * 'includeFields' => string[] RecentChange fields to be included in the result,
113 * self::INCLUDE_* constants should be used
114 * 'filters' => string[] optional filters to narrow down resulted items
115 * 'namespaceIds' => int[] optional namespace IDs to filter by
116 * (defaults to all namespaces)
117 * 'allRevisions' => bool return multiple revisions of the same page if true,
118 * only the most recent if false (default)
119 * 'rcTypes' => int[] which types of RecentChanges to include
120 * (defaults to all types), allowed values: RC_EDIT, RC_NEW,
121 * RC_LOG, RC_EXTERNAL, RC_CATEGORIZE
122 * 'onlyByUser' => string only list changes by a specified user
123 * 'notByUser' => string do not incluide changes by a specified user
124 * 'dir' => string in which direction to enumerate, accepted values:
125 * - DIR_OLDER list newest first
126 * - DIR_NEWER list oldest first
127 * 'start' => string (format accepted by wfTimestamp) requires 'dir' option,
128 * timestamp to start enumerating from
129 * 'end' => string (format accepted by wfTimestamp) requires 'dir' option,
130 * timestamp to end enumerating
131 * 'watchlistOwner' => User user whose watchlist items should be listed if different
132 * than the one specified with $user param, requires
133 * 'watchlistOwnerToken' option
134 * 'watchlistOwnerToken' => string a watchlist token used to access another user's
135 * watchlist, used with 'watchlistOwnerToken' option
136 * 'limit' => int maximum numbers of items to return
137 * 'usedInGenerator' => bool include only RecentChange id field required by the
138 * generator ('rc_cur_id' or 'rc_this_oldid') if true, or all
139 * id fields ('rc_cur_id', 'rc_this_oldid', 'rc_last_oldid')
140 * if false (default)
141 * @param array|null &$startFrom Continuation value: [ string $rcTimestamp, int $rcId ]
142 * @return array[] Array of pairs ( WatchedItem $watchedItem, string[] $recentChangeInfo ),
143 * where $recentChangeInfo contains the following keys:
144 * - 'rc_id',
145 * - 'rc_namespace',
146 * - 'rc_title',
147 * - 'rc_timestamp',
148 * - 'rc_type',
149 * - 'rc_deleted',
150 * Additional keys could be added by specifying the 'includeFields' option
151 */
152 public function getWatchedItemsWithRecentChangeInfo(
153 User $user, array $options = [], &$startFrom = null
154 ) {
155 $options += [
156 'includeFields' => [],
157 'namespaceIds' => [],
158 'filters' => [],
159 'allRevisions' => false,
160 'usedInGenerator' => false
161 ];
162
163 Assert::parameter(
164 !isset( $options['rcTypes'] )
165 || !array_diff( $options['rcTypes'], [ RC_EDIT, RC_NEW, RC_LOG, RC_EXTERNAL, RC_CATEGORIZE ] ),
166 '$options[\'rcTypes\']',
167 'must be an array containing only: RC_EDIT, RC_NEW, RC_LOG, RC_EXTERNAL and/or RC_CATEGORIZE'
168 );
169 Assert::parameter(
170 !isset( $options['dir'] ) || in_array( $options['dir'], [ self::DIR_OLDER, self::DIR_NEWER ] ),
171 '$options[\'dir\']',
172 'must be DIR_OLDER or DIR_NEWER'
173 );
174 Assert::parameter(
175 !isset( $options['start'] ) && !isset( $options['end'] ) && $startFrom === null
176 || isset( $options['dir'] ),
177 '$options[\'dir\']',
178 'must be provided when providing the "start" or "end" options or the $startFrom parameter'
179 );
180 Assert::parameter(
181 !isset( $options['startFrom'] ),
182 '$options[\'startFrom\']',
183 'must not be provided, use $startFrom instead'
184 );
185 Assert::parameter(
186 !isset( $startFrom ) || ( is_array( $startFrom ) && count( $startFrom ) === 2 ),
187 '$startFrom',
188 'must be a two-element array'
189 );
190 if ( array_key_exists( 'watchlistOwner', $options ) ) {
191 Assert::parameterType(
192 User::class,
193 $options['watchlistOwner'],
194 '$options[\'watchlistOwner\']'
195 );
196 Assert::parameter(
197 isset( $options['watchlistOwnerToken'] ),
198 '$options[\'watchlistOwnerToken\']',
199 'must be provided when providing watchlistOwner option'
200 );
201 }
202
203 $db = $this->getConnection();
204
205 $tables = $this->getWatchedItemsWithRCInfoQueryTables( $options );
206 $fields = $this->getWatchedItemsWithRCInfoQueryFields( $options );
207 $conds = $this->getWatchedItemsWithRCInfoQueryConds( $db, $user, $options );
208 $dbOptions = $this->getWatchedItemsWithRCInfoQueryDbOptions( $options );
209 $joinConds = $this->getWatchedItemsWithRCInfoQueryJoinConds( $options );
210
211 if ( $startFrom !== null ) {
212 $conds[] = $this->getStartFromConds( $db, $options, $startFrom );
213 }
214
215 foreach ( $this->getExtensions() as $extension ) {
216 $extension->modifyWatchedItemsWithRCInfoQuery(
217 $user, $options, $db,
218 $tables,
219 $fields,
220 $conds,
221 $dbOptions,
222 $joinConds
223 );
224 }
225
226 $res = $db->select(
227 $tables,
228 $fields,
229 $conds,
230 __METHOD__,
231 $dbOptions,
232 $joinConds
233 );
234
235 $limit = $dbOptions['LIMIT'] ?? INF;
236 $items = [];
237 $startFrom = null;
238 foreach ( $res as $row ) {
239 if ( --$limit <= 0 ) {
240 $startFrom = [ $row->rc_timestamp, $row->rc_id ];
241 break;
242 }
243
244 $target = new TitleValue( (int)$row->rc_namespace, $row->rc_title );
245 $items[] = [
246 new WatchedItem(
247 $user,
248 $target,
249 $this->watchedItemStore->getLatestNotificationTimestamp(
250 $row->wl_notificationtimestamp, $user, $target
251 )
252 ),
253 $this->getRecentChangeFieldsFromRow( $row )
254 ];
255 }
256
257 foreach ( $this->getExtensions() as $extension ) {
258 $extension->modifyWatchedItemsWithRCInfo( $user, $options, $db, $items, $res, $startFrom );
259 }
260
261 return $items;
262 }
263
264 /**
265 * For simple listing of user's watchlist items, see WatchedItemStore::getWatchedItemsForUser
266 *
267 * @param UserIdentity $user
268 * @param array $options Allowed keys:
269 * 'sort' => string optional sorting by namespace ID and title
270 * one of the self::SORT_* constants
271 * 'namespaceIds' => int[] optional namespace IDs to filter by (defaults to all namespaces)
272 * 'limit' => int maximum number of items to return
273 * 'filter' => string optional filter, one of the self::FILTER_* contants
274 * 'from' => LinkTarget requires 'sort' key, only return items starting from
275 * those related to the link target
276 * 'until' => LinkTarget requires 'sort' key, only return items until
277 * those related to the link target
278 * 'startFrom' => LinkTarget requires 'sort' key, only return items starting from
279 * those related to the link target, allows to skip some link targets
280 * specified using the form option
281 * @return WatchedItem[]
282 */
283 public function getWatchedItemsForUser( UserIdentity $user, array $options = [] ) {
284 if ( !$user->isRegistered() ) {
285 // TODO: should this just return an empty array or rather complain loud at this point
286 // as e.g. ApiBase::getWatchlistUser does?
287 return [];
288 }
289
290 $options += [ 'namespaceIds' => [] ];
291
292 Assert::parameter(
293 !isset( $options['sort'] ) || in_array( $options['sort'], [ self::SORT_ASC, self::SORT_DESC ] ),
294 '$options[\'sort\']',
295 'must be SORT_ASC or SORT_DESC'
296 );
297 Assert::parameter(
298 !isset( $options['filter'] ) || in_array(
299 $options['filter'], [ self::FILTER_CHANGED, self::FILTER_NOT_CHANGED ]
300 ),
301 '$options[\'filter\']',
302 'must be FILTER_CHANGED or FILTER_NOT_CHANGED'
303 );
304 Assert::parameter(
305 !isset( $options['from'] ) && !isset( $options['until'] ) && !isset( $options['startFrom'] )
306 || isset( $options['sort'] ),
307 '$options[\'sort\']',
308 'must be provided if any of "from", "until", "startFrom" options is provided'
309 );
310
311 $db = $this->getConnection();
312
313 $conds = $this->getWatchedItemsForUserQueryConds( $db, $user, $options );
314 $dbOptions = $this->getWatchedItemsForUserQueryDbOptions( $options );
315
316 $res = $db->select(
317 'watchlist',
318 [ 'wl_namespace', 'wl_title', 'wl_notificationtimestamp' ],
319 $conds,
320 __METHOD__,
321 $dbOptions
322 );
323
324 $watchedItems = [];
325 foreach ( $res as $row ) {
326 $target = new TitleValue( (int)$row->wl_namespace, $row->wl_title );
327 // todo these could all be cached at some point?
328 $watchedItems[] = new WatchedItem(
329 $user,
330 $target,
331 $this->watchedItemStore->getLatestNotificationTimestamp(
332 $row->wl_notificationtimestamp, $user, $target
333 )
334 );
335 }
336
337 return $watchedItems;
338 }
339
340 private function getRecentChangeFieldsFromRow( stdClass $row ) {
341 // FIXME: This can be simplified to single array_filter call filtering by key value,
342 // now we have stopped supporting PHP 5.5
343 $allFields = get_object_vars( $row );
344 $rcKeys = array_filter(
345 array_keys( $allFields ),
346 function ( $key ) {
347 return substr( $key, 0, 3 ) === 'rc_';
348 }
349 );
350 return array_intersect_key( $allFields, array_flip( $rcKeys ) );
351 }
352
353 private function getWatchedItemsWithRCInfoQueryTables( array $options ) {
354 $tables = [ 'recentchanges', 'watchlist' ];
355 if ( !$options['allRevisions'] ) {
356 $tables[] = 'page';
357 }
358 if ( in_array( self::INCLUDE_COMMENT, $options['includeFields'] ) ) {
359 $tables += $this->commentStore->getJoin( 'rc_comment' )['tables'];
360 }
361 if ( in_array( self::INCLUDE_USER, $options['includeFields'] ) ||
362 in_array( self::INCLUDE_USER_ID, $options['includeFields'] ) ||
363 in_array( self::FILTER_ANON, $options['filters'] ) ||
364 in_array( self::FILTER_NOT_ANON, $options['filters'] ) ||
365 array_key_exists( 'onlyByUser', $options ) || array_key_exists( 'notByUser', $options )
366 ) {
367 $tables += $this->actorMigration->getJoin( 'rc_user' )['tables'];
368 }
369 return $tables;
370 }
371
372 private function getWatchedItemsWithRCInfoQueryFields( array $options ) {
373 $fields = [
374 'rc_id',
375 'rc_namespace',
376 'rc_title',
377 'rc_timestamp',
378 'rc_type',
379 'rc_deleted',
380 'wl_notificationtimestamp'
381 ];
382
383 $rcIdFields = [
384 'rc_cur_id',
385 'rc_this_oldid',
386 'rc_last_oldid',
387 ];
388 if ( $options['usedInGenerator'] ) {
389 if ( $options['allRevisions'] ) {
390 $rcIdFields = [ 'rc_this_oldid' ];
391 } else {
392 $rcIdFields = [ 'rc_cur_id' ];
393 }
394 }
395 $fields = array_merge( $fields, $rcIdFields );
396
397 if ( in_array( self::INCLUDE_FLAGS, $options['includeFields'] ) ) {
398 $fields = array_merge( $fields, [ 'rc_type', 'rc_minor', 'rc_bot' ] );
399 }
400 if ( in_array( self::INCLUDE_USER, $options['includeFields'] ) ) {
401 $fields['rc_user_text'] = $this->actorMigration->getJoin( 'rc_user' )['fields']['rc_user_text'];
402 }
403 if ( in_array( self::INCLUDE_USER_ID, $options['includeFields'] ) ) {
404 $fields['rc_user'] = $this->actorMigration->getJoin( 'rc_user' )['fields']['rc_user'];
405 }
406 if ( in_array( self::INCLUDE_COMMENT, $options['includeFields'] ) ) {
407 $fields += $this->commentStore->getJoin( 'rc_comment' )['fields'];
408 }
409 if ( in_array( self::INCLUDE_PATROL_INFO, $options['includeFields'] ) ) {
410 $fields = array_merge( $fields, [ 'rc_patrolled', 'rc_log_type' ] );
411 }
412 if ( in_array( self::INCLUDE_SIZES, $options['includeFields'] ) ) {
413 $fields = array_merge( $fields, [ 'rc_old_len', 'rc_new_len' ] );
414 }
415 if ( in_array( self::INCLUDE_LOG_INFO, $options['includeFields'] ) ) {
416 $fields = array_merge( $fields, [ 'rc_logid', 'rc_log_type', 'rc_log_action', 'rc_params' ] );
417 }
418 if ( in_array( self::INCLUDE_TAGS, $options['includeFields'] ) ) {
419 // prefixed with rc_ to include the field in getRecentChangeFieldsFromRow
420 $fields['rc_tags'] = ChangeTags::makeTagSummarySubquery( 'recentchanges' );
421 }
422
423 return $fields;
424 }
425
426 private function getWatchedItemsWithRCInfoQueryConds(
427 IDatabase $db,
428 User $user,
429 array $options
430 ) {
431 $watchlistOwnerId = $this->getWatchlistOwnerId( $user, $options );
432 $conds = [ 'wl_user' => $watchlistOwnerId ];
433
434 if ( !$options['allRevisions'] ) {
435 $conds[] = $db->makeList(
436 [ 'rc_this_oldid=page_latest', 'rc_type=' . RC_LOG ],
437 LIST_OR
438 );
439 }
440
441 if ( $options['namespaceIds'] ) {
442 $conds['wl_namespace'] = array_map( 'intval', $options['namespaceIds'] );
443 }
444
445 if ( array_key_exists( 'rcTypes', $options ) ) {
446 $conds['rc_type'] = array_map( 'intval', $options['rcTypes'] );
447 }
448
449 $conds = array_merge(
450 $conds,
451 $this->getWatchedItemsWithRCInfoQueryFilterConds( $user, $options )
452 );
453
454 $conds = array_merge( $conds, $this->getStartEndConds( $db, $options ) );
455
456 if ( !isset( $options['start'] ) && !isset( $options['end'] ) && $db->getType() === 'mysql' ) {
457 // This is an index optimization for mysql
458 $conds[] = 'rc_timestamp > ' . $db->addQuotes( '' );
459 }
460
461 $conds = array_merge( $conds, $this->getUserRelatedConds( $db, $user, $options ) );
462
463 $deletedPageLogCond = $this->getExtraDeletedPageLogEntryRelatedCond( $db, $user );
464 if ( $deletedPageLogCond ) {
465 $conds[] = $deletedPageLogCond;
466 }
467
468 return $conds;
469 }
470
471 private function getWatchlistOwnerId( UserIdentity $user, array $options ) {
472 if ( array_key_exists( 'watchlistOwner', $options ) ) {
473 /** @var User $watchlistOwner */
474 $watchlistOwner = $options['watchlistOwner'];
475 $ownersToken =
476 $watchlistOwner->getOption( 'watchlisttoken' );
477 $token = $options['watchlistOwnerToken'];
478 if ( $ownersToken == '' || !hash_equals( $ownersToken, $token ) ) {
479 throw ApiUsageException::newWithMessage( null, 'apierror-bad-watchlist-token', 'bad_wltoken' );
480 }
481 return $watchlistOwner->getId();
482 }
483 return $user->getId();
484 }
485
486 private function getWatchedItemsWithRCInfoQueryFilterConds( User $user, array $options ) {
487 $conds = [];
488
489 if ( in_array( self::FILTER_MINOR, $options['filters'] ) ) {
490 $conds[] = 'rc_minor != 0';
491 } elseif ( in_array( self::FILTER_NOT_MINOR, $options['filters'] ) ) {
492 $conds[] = 'rc_minor = 0';
493 }
494
495 if ( in_array( self::FILTER_BOT, $options['filters'] ) ) {
496 $conds[] = 'rc_bot != 0';
497 } elseif ( in_array( self::FILTER_NOT_BOT, $options['filters'] ) ) {
498 $conds[] = 'rc_bot = 0';
499 }
500
501 if ( in_array( self::FILTER_ANON, $options['filters'] ) ) {
502 $conds[] = $this->actorMigration->isAnon(
503 $this->actorMigration->getJoin( 'rc_user' )['fields']['rc_user']
504 );
505 } elseif ( in_array( self::FILTER_NOT_ANON, $options['filters'] ) ) {
506 $conds[] = $this->actorMigration->isNotAnon(
507 $this->actorMigration->getJoin( 'rc_user' )['fields']['rc_user']
508 );
509 }
510
511 if ( $user->useRCPatrol() || $user->useNPPatrol() ) {
512 // TODO: not sure if this should simply ignore patrolled filters if user does not have the patrol
513 // right, or maybe rather fail loud at this point, same as e.g. ApiQueryWatchlist does?
514 if ( in_array( self::FILTER_PATROLLED, $options['filters'] ) ) {
515 $conds[] = 'rc_patrolled != ' . RecentChange::PRC_UNPATROLLED;
516 } elseif ( in_array( self::FILTER_NOT_PATROLLED, $options['filters'] ) ) {
517 $conds['rc_patrolled'] = RecentChange::PRC_UNPATROLLED;
518 }
519
520 if ( in_array( self::FILTER_AUTOPATROLLED, $options['filters'] ) ) {
521 $conds['rc_patrolled'] = RecentChange::PRC_AUTOPATROLLED;
522 } elseif ( in_array( self::FILTER_NOT_AUTOPATROLLED, $options['filters'] ) ) {
523 $conds[] = 'rc_patrolled != ' . RecentChange::PRC_AUTOPATROLLED;
524 }
525 }
526
527 if ( in_array( self::FILTER_UNREAD, $options['filters'] ) ) {
528 $conds[] = 'rc_timestamp >= wl_notificationtimestamp';
529 } elseif ( in_array( self::FILTER_NOT_UNREAD, $options['filters'] ) ) {
530 // TODO: should this be changed to use Database::makeList?
531 $conds[] = 'wl_notificationtimestamp IS NULL OR rc_timestamp < wl_notificationtimestamp';
532 }
533
534 return $conds;
535 }
536
537 private function getStartEndConds( IDatabase $db, array $options ) {
538 if ( !isset( $options['start'] ) && !isset( $options['end'] ) ) {
539 return [];
540 }
541
542 $conds = [];
543
544 if ( isset( $options['start'] ) ) {
545 $after = $options['dir'] === self::DIR_OLDER ? '<=' : '>=';
546 $conds[] = 'rc_timestamp ' . $after . ' ' .
547 $db->addQuotes( $db->timestamp( $options['start'] ) );
548 }
549 if ( isset( $options['end'] ) ) {
550 $before = $options['dir'] === self::DIR_OLDER ? '>=' : '<=';
551 $conds[] = 'rc_timestamp ' . $before . ' ' .
552 $db->addQuotes( $db->timestamp( $options['end'] ) );
553 }
554
555 return $conds;
556 }
557
558 private function getUserRelatedConds( IDatabase $db, UserIdentity $user, array $options ) {
559 if ( !array_key_exists( 'onlyByUser', $options ) && !array_key_exists( 'notByUser', $options ) ) {
560 return [];
561 }
562
563 $conds = [];
564
565 if ( array_key_exists( 'onlyByUser', $options ) ) {
566 $byUser = User::newFromName( $options['onlyByUser'], false );
567 $conds[] = $this->actorMigration->getWhere( $db, 'rc_user', $byUser )['conds'];
568 } elseif ( array_key_exists( 'notByUser', $options ) ) {
569 $byUser = User::newFromName( $options['notByUser'], false );
570 $conds[] = 'NOT(' . $this->actorMigration->getWhere( $db, 'rc_user', $byUser )['conds'] . ')';
571 }
572
573 // Avoid brute force searches (T19342)
574 $bitmask = 0;
575 if ( !$this->permissionManager->userHasRight( $user, 'deletedhistory' ) ) {
576 $bitmask = RevisionRecord::DELETED_USER;
577 } elseif ( !$this->permissionManager
578 ->userHasAnyRight( $user, 'suppressrevision', 'viewsuppressed' )
579 ) {
580 $bitmask = RevisionRecord::DELETED_USER | RevisionRecord::DELETED_RESTRICTED;
581 }
582 if ( $bitmask ) {
583 $conds[] = $db->bitAnd( 'rc_deleted', $bitmask ) . " != $bitmask";
584 }
585
586 return $conds;
587 }
588
589 private function getExtraDeletedPageLogEntryRelatedCond( IDatabase $db, UserIdentity $user ) {
590 // LogPage::DELETED_ACTION hides the affected page, too. So hide those
591 // entirely from the watchlist, or someone could guess the title.
592 $bitmask = 0;
593 if ( !$this->permissionManager->userHasRight( $user, 'deletedhistory' ) ) {
594 $bitmask = LogPage::DELETED_ACTION;
595 } elseif ( !$this->permissionManager
596 ->userHasAnyRight( $user, 'suppressrevision', 'viewsuppressed' )
597 ) {
598 $bitmask = LogPage::DELETED_ACTION | LogPage::DELETED_RESTRICTED;
599 }
600 if ( $bitmask ) {
601 return $db->makeList( [
602 'rc_type != ' . RC_LOG,
603 $db->bitAnd( 'rc_deleted', $bitmask ) . " != $bitmask",
604 ], LIST_OR );
605 }
606 return '';
607 }
608
609 private function getStartFromConds( IDatabase $db, array $options, array $startFrom ) {
610 $op = $options['dir'] === self::DIR_OLDER ? '<' : '>';
611 list( $rcTimestamp, $rcId ) = $startFrom;
612 $rcTimestamp = $db->addQuotes( $db->timestamp( $rcTimestamp ) );
613 $rcId = (int)$rcId;
614 return $db->makeList(
615 [
616 "rc_timestamp $op $rcTimestamp",
617 $db->makeList(
618 [
619 "rc_timestamp = $rcTimestamp",
620 "rc_id $op= $rcId"
621 ],
622 LIST_AND
623 )
624 ],
625 LIST_OR
626 );
627 }
628
629 private function getWatchedItemsForUserQueryConds(
630 IDatabase $db, UserIdentity $user, array $options
631 ) {
632 $conds = [ 'wl_user' => $user->getId() ];
633 if ( $options['namespaceIds'] ) {
634 $conds['wl_namespace'] = array_map( 'intval', $options['namespaceIds'] );
635 }
636 if ( isset( $options['filter'] ) ) {
637 $filter = $options['filter'];
638 if ( $filter === self::FILTER_CHANGED ) {
639 $conds[] = 'wl_notificationtimestamp IS NOT NULL';
640 } else {
641 $conds[] = 'wl_notificationtimestamp IS NULL';
642 }
643 }
644
645 if ( isset( $options['from'] ) ) {
646 $op = $options['sort'] === self::SORT_ASC ? '>' : '<';
647 $conds[] = $this->getFromUntilTargetConds( $db, $options['from'], $op );
648 }
649 if ( isset( $options['until'] ) ) {
650 $op = $options['sort'] === self::SORT_ASC ? '<' : '>';
651 $conds[] = $this->getFromUntilTargetConds( $db, $options['until'], $op );
652 }
653 if ( isset( $options['startFrom'] ) ) {
654 $op = $options['sort'] === self::SORT_ASC ? '>' : '<';
655 $conds[] = $this->getFromUntilTargetConds( $db, $options['startFrom'], $op );
656 }
657
658 return $conds;
659 }
660
661 /**
662 * Creates a query condition part for getting only items before or after the given link target
663 * (while ordering using $sort mode)
664 *
665 * @param IDatabase $db
666 * @param LinkTarget $target
667 * @param string $op comparison operator to use in the conditions
668 * @return string
669 */
670 private function getFromUntilTargetConds( IDatabase $db, LinkTarget $target, $op ) {
671 return $db->makeList(
672 [
673 "wl_namespace $op " . $target->getNamespace(),
674 $db->makeList(
675 [
676 'wl_namespace = ' . $target->getNamespace(),
677 "wl_title $op= " . $db->addQuotes( $target->getDBkey() )
678 ],
679 LIST_AND
680 )
681 ],
682 LIST_OR
683 );
684 }
685
686 private function getWatchedItemsWithRCInfoQueryDbOptions( array $options ) {
687 $dbOptions = [];
688
689 if ( array_key_exists( 'dir', $options ) ) {
690 $sort = $options['dir'] === self::DIR_OLDER ? ' DESC' : '';
691 $dbOptions['ORDER BY'] = [ 'rc_timestamp' . $sort, 'rc_id' . $sort ];
692 }
693
694 if ( array_key_exists( 'limit', $options ) ) {
695 $dbOptions['LIMIT'] = (int)$options['limit'] + 1;
696 }
697
698 return $dbOptions;
699 }
700
701 private function getWatchedItemsForUserQueryDbOptions( array $options ) {
702 $dbOptions = [];
703 if ( array_key_exists( 'sort', $options ) ) {
704 $dbOptions['ORDER BY'] = [
705 "wl_namespace {$options['sort']}",
706 "wl_title {$options['sort']}"
707 ];
708 if ( count( $options['namespaceIds'] ) === 1 ) {
709 $dbOptions['ORDER BY'] = "wl_title {$options['sort']}";
710 }
711 }
712 if ( array_key_exists( 'limit', $options ) ) {
713 $dbOptions['LIMIT'] = (int)$options['limit'];
714 }
715 return $dbOptions;
716 }
717
718 private function getWatchedItemsWithRCInfoQueryJoinConds( array $options ) {
719 $joinConds = [
720 'watchlist' => [ 'JOIN',
721 [
722 'wl_namespace=rc_namespace',
723 'wl_title=rc_title'
724 ]
725 ]
726 ];
727 if ( !$options['allRevisions'] ) {
728 $joinConds['page'] = [ 'LEFT JOIN', 'rc_cur_id=page_id' ];
729 }
730 if ( in_array( self::INCLUDE_COMMENT, $options['includeFields'] ) ) {
731 $joinConds += $this->commentStore->getJoin( 'rc_comment' )['joins'];
732 }
733 if ( in_array( self::INCLUDE_USER, $options['includeFields'] ) ||
734 in_array( self::INCLUDE_USER_ID, $options['includeFields'] ) ||
735 in_array( self::FILTER_ANON, $options['filters'] ) ||
736 in_array( self::FILTER_NOT_ANON, $options['filters'] ) ||
737 array_key_exists( 'onlyByUser', $options ) || array_key_exists( 'notByUser', $options )
738 ) {
739 $joinConds += $this->actorMigration->getJoin( 'rc_user' )['joins'];
740 }
741 return $joinConds;
742 }
743
744 }