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