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