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