Merge "WLFilters: fix server-side tag filtering"
[lhc/web/wiklou.git] / includes / specials / SpecialRecentchanges.php
1 <?php
2 /**
3 * Implements Special:Recentchanges
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup SpecialPage
22 */
23
24 use MediaWiki\MediaWikiServices;
25 use Wikimedia\Rdbms\ResultWrapper;
26 use Wikimedia\Rdbms\FakeResultWrapper;
27
28 /**
29 * A special page that lists last changes made to the wiki
30 *
31 * @ingroup SpecialPage
32 */
33 class SpecialRecentChanges extends ChangesListSpecialPage {
34
35 private $watchlistFilterGroupDefinition;
36
37 // @codingStandardsIgnoreStart Needed "useless" override to change parameters.
38 public function __construct( $name = 'Recentchanges', $restriction = '' ) {
39 parent::__construct( $name, $restriction );
40
41 $this->watchlistFilterGroupDefinition = [
42 'name' => 'watchlist',
43 'title' => 'rcfilters-filtergroup-watchlist',
44 'class' => ChangesListStringOptionsFilterGroup::class,
45 'priority' => -9,
46 'isFullCoverage' => true,
47 'filters' => [
48 [
49 'name' => 'watched',
50 'label' => 'rcfilters-filter-watchlist-watched-label',
51 'description' => 'rcfilters-filter-watchlist-watched-description',
52 'cssClassSuffix' => 'watched',
53 'isRowApplicableCallable' => function ( $ctx, $rc ) {
54 return $rc->getAttribute( 'wl_user' );
55 }
56 ],
57 [
58 'name' => 'watchednew',
59 'label' => 'rcfilters-filter-watchlist-watchednew-label',
60 'description' => 'rcfilters-filter-watchlist-watchednew-description',
61 'cssClassSuffix' => 'watchednew',
62 'isRowApplicableCallable' => function ( $ctx, $rc ) {
63 return $rc->getAttribute( 'wl_user' ) &&
64 $rc->getAttribute( 'rc_timestamp' ) &&
65 $rc->getAttribute( 'wl_notificationtimestamp' ) &&
66 $rc->getAttribute( 'rc_timestamp' ) >= $rc->getAttribute( 'wl_notificationtimestamp' );
67 },
68 ],
69 [
70 'name' => 'notwatched',
71 'label' => 'rcfilters-filter-watchlist-notwatched-label',
72 'description' => 'rcfilters-filter-watchlist-notwatched-description',
73 'cssClassSuffix' => 'notwatched',
74 'isRowApplicableCallable' => function ( $ctx, $rc ) {
75 return $rc->getAttribute( 'wl_user' ) === null;
76 },
77 ]
78 ],
79 'default' => ChangesListStringOptionsFilterGroup::NONE,
80 'queryCallable' => function ( $specialPageClassName, $context, $dbr,
81 &$tables, &$fields, &$conds, &$query_options, &$join_conds, $selectedValues ) {
82 sort( $selectedValues );
83 $notwatchedCond = 'wl_user IS NULL';
84 $watchedCond = 'wl_user IS NOT NULL';
85 $newCond = 'rc_timestamp >= wl_notificationtimestamp';
86
87 if ( $selectedValues === [ 'notwatched' ] ) {
88 $conds[] = $notwatchedCond;
89 return;
90 }
91
92 if ( $selectedValues === [ 'watched' ] ) {
93 $conds[] = $watchedCond;
94 return;
95 }
96
97 if ( $selectedValues === [ 'watchednew' ] ) {
98 $conds[] = $dbr->makeList( [
99 $watchedCond,
100 $newCond
101 ], LIST_AND );
102 return;
103 }
104
105 if ( $selectedValues === [ 'notwatched', 'watched' ] ) {
106 // no filters
107 return;
108 }
109
110 if ( $selectedValues === [ 'notwatched', 'watchednew' ] ) {
111 $conds[] = $dbr->makeList( [
112 $notwatchedCond,
113 $dbr->makeList( [
114 $watchedCond,
115 $newCond
116 ], LIST_AND )
117 ], LIST_OR );
118 return;
119 }
120
121 if ( $selectedValues === [ 'watched', 'watchednew' ] ) {
122 $conds[] = $watchedCond;
123 return;
124 }
125
126 if ( $selectedValues === [ 'notwatched', 'watched', 'watchednew' ] ) {
127 // no filters
128 return;
129 }
130 }
131 ];
132 }
133 // @codingStandardsIgnoreEnd
134
135 /**
136 * Main execution point
137 *
138 * @param string $subpage
139 */
140 public function execute( $subpage ) {
141 // Backwards-compatibility: redirect to new feed URLs
142 $feedFormat = $this->getRequest()->getVal( 'feed' );
143 if ( !$this->including() && $feedFormat ) {
144 $query = $this->getFeedQuery();
145 $query['feedformat'] = $feedFormat === 'atom' ? 'atom' : 'rss';
146 $this->getOutput()->redirect( wfAppendQuery( wfScript( 'api' ), $query ) );
147
148 return;
149 }
150
151 // 10 seconds server-side caching max
152 $out = $this->getOutput();
153 $out->setCdnMaxage( 10 );
154 // Check if the client has a cached version
155 $lastmod = $this->checkLastModified();
156 if ( $lastmod === false ) {
157 return;
158 }
159
160 $this->addHelpLink(
161 '//meta.wikimedia.org/wiki/Special:MyLanguage/Help:Recent_changes',
162 true
163 );
164 parent::execute( $subpage );
165
166 if ( $this->isStructuredFilterUiEnabled() ) {
167 $out->addJsConfigVars( 'wgStructuredChangeFiltersLiveUpdateSupported', true );
168 $out->addJsConfigVars(
169 'wgStructuredChangeFiltersSavedQueriesPreferenceName',
170 'rcfilters-saved-queries'
171 );
172 }
173 }
174
175 /**
176 * @inheritDoc
177 */
178 protected function transformFilterDefinition( array $filterDefinition ) {
179 if ( isset( $filterDefinition['showHideSuffix'] ) ) {
180 $filterDefinition['showHide'] = 'rc' . $filterDefinition['showHideSuffix'];
181 }
182
183 return $filterDefinition;
184 }
185
186 /**
187 * @inheritDoc
188 */
189 protected function registerFilters() {
190 parent::registerFilters();
191
192 if (
193 !$this->including() &&
194 $this->getUser()->isLoggedIn() &&
195 $this->getUser()->isAllowed( 'viewmywatchlist' )
196 ) {
197 $this->registerFiltersFromDefinitions( [ $this->watchlistFilterGroupDefinition ] );
198 $watchlistGroup = $this->getFilterGroup( 'watchlist' );
199 $watchlistGroup->getFilter( 'watched' )->setAsSupersetOf(
200 $watchlistGroup->getFilter( 'watchednew' )
201 );
202 }
203
204 $user = $this->getUser();
205
206 $significance = $this->getFilterGroup( 'significance' );
207 $hideMinor = $significance->getFilter( 'hideminor' );
208 $hideMinor->setDefault( $user->getBoolOption( 'hideminor' ) );
209
210 $automated = $this->getFilterGroup( 'automated' );
211 $hideBots = $automated->getFilter( 'hidebots' );
212 $hideBots->setDefault( true );
213
214 $reviewStatus = $this->getFilterGroup( 'reviewStatus' );
215 if ( $reviewStatus !== null ) {
216 // Conditional on feature being available and rights
217 $hidePatrolled = $reviewStatus->getFilter( 'hidepatrolled' );
218 $hidePatrolled->setDefault( $user->getBoolOption( 'hidepatrolled' ) );
219 }
220
221 $changeType = $this->getFilterGroup( 'changeType' );
222 $hideCategorization = $changeType->getFilter( 'hidecategorization' );
223 if ( $hideCategorization !== null ) {
224 // Conditional on feature being available
225 $hideCategorization->setDefault( $user->getBoolOption( 'hidecategorization' ) );
226 }
227 }
228
229 /**
230 * Get a FormOptions object containing the default options
231 *
232 * @return FormOptions
233 */
234 public function getDefaultOptions() {
235 $opts = parent::getDefaultOptions();
236 $user = $this->getUser();
237
238 $opts->add( 'days', $user->getIntOption( 'rcdays' ), FormOptions::FLOAT );
239 $opts->add( 'limit', $user->getIntOption( 'rclimit' ) );
240 $opts->add( 'from', '' );
241
242 $opts->add( 'categories', '' );
243 $opts->add( 'categories_any', false );
244
245 return $opts;
246 }
247
248 /**
249 * Get all custom filters
250 *
251 * @return array Map of filter URL param names to properties (msg/default)
252 */
253 protected function getCustomFilters() {
254 if ( $this->customFilters === null ) {
255 $this->customFilters = parent::getCustomFilters();
256 Hooks::run( 'SpecialRecentChangesFilters', [ $this, &$this->customFilters ], '1.23' );
257 }
258
259 return $this->customFilters;
260 }
261
262 /**
263 * Process $par and put options found in $opts. Used when including the page.
264 *
265 * @param string $par
266 * @param FormOptions $opts
267 */
268 public function parseParameters( $par, FormOptions $opts ) {
269 parent::parseParameters( $par, $opts );
270
271 $bits = preg_split( '/\s*,\s*/', trim( $par ) );
272 foreach ( $bits as $bit ) {
273 if ( is_numeric( $bit ) ) {
274 $opts['limit'] = $bit;
275 }
276
277 $m = [];
278 if ( preg_match( '/^limit=(\d+)$/', $bit, $m ) ) {
279 $opts['limit'] = $m[1];
280 }
281 if ( preg_match( '/^days=(\d+(?:\.\d+)?)$/', $bit, $m ) ) {
282 $opts['days'] = $m[1];
283 }
284 if ( preg_match( '/^namespace=(.*)$/', $bit, $m ) ) {
285 $opts['namespace'] = $m[1];
286 }
287 if ( preg_match( '/^tagfilter=(.*)$/', $bit, $m ) ) {
288 $opts['tagfilter'] = $m[1];
289 }
290 }
291 }
292
293 public function validateOptions( FormOptions $opts ) {
294 $opts->validateIntBounds( 'limit', 0, 5000 );
295 $opts->validateBounds( 'days', 0, $this->getConfig()->get( 'RCMaxAge' ) / ( 3600 * 24 ) );
296 parent::validateOptions( $opts );
297 }
298
299 /**
300 * @inheritDoc
301 */
302 protected function buildQuery( &$tables, &$fields, &$conds,
303 &$query_options, &$join_conds, FormOptions $opts
304 ) {
305 $dbr = $this->getDB();
306 parent::buildQuery( $tables, $fields, $conds,
307 $query_options, $join_conds, $opts );
308
309 // Calculate cutoff
310 $cutoff_unixtime = time() - $opts['days'] * 3600 * 24;
311 $cutoff = $dbr->timestamp( $cutoff_unixtime );
312
313 $fromValid = preg_match( '/^[0-9]{14}$/', $opts['from'] );
314 if ( $fromValid && $opts['from'] > wfTimestamp( TS_MW, $cutoff ) ) {
315 $cutoff = $dbr->timestamp( $opts['from'] );
316 } else {
317 $opts->reset( 'from' );
318 }
319
320 $conds[] = 'rc_timestamp >= ' . $dbr->addQuotes( $cutoff );
321 }
322
323 /**
324 * @inheritDoc
325 */
326 protected function doMainQuery( $tables, $fields, $conds, $query_options,
327 $join_conds, FormOptions $opts
328 ) {
329 $dbr = $this->getDB();
330 $user = $this->getUser();
331
332 $tables[] = 'recentchanges';
333 $fields = array_merge( RecentChange::selectFields(), $fields );
334
335 // JOIN on watchlist for users
336 if ( $user->isLoggedIn() && $user->isAllowed( 'viewmywatchlist' ) ) {
337 $tables[] = 'watchlist';
338 $fields[] = 'wl_user';
339 $fields[] = 'wl_notificationtimestamp';
340 $join_conds['watchlist'] = [ 'LEFT JOIN', [
341 'wl_user' => $user->getId(),
342 'wl_title=rc_title',
343 'wl_namespace=rc_namespace'
344 ] ];
345 }
346
347 // JOIN on page, used for 'last revision' filter highlight
348 $tables[] = 'page';
349 $fields[] = 'page_latest';
350 $join_conds['page'] = [ 'LEFT JOIN', 'rc_cur_id=page_id' ];
351
352 $tagFilter = $opts['tagfilter'] ? explode( '|', $opts['tagfilter'] ) : [];
353 ChangeTags::modifyDisplayQuery(
354 $tables,
355 $fields,
356 $conds,
357 $join_conds,
358 $query_options,
359 $tagFilter
360 );
361
362 if ( !$this->runMainQueryHook( $tables, $fields, $conds, $query_options, $join_conds,
363 $opts )
364 ) {
365 return false;
366 }
367
368 if ( $this->areFiltersInConflict() ) {
369 return false;
370 }
371
372 $orderByAndLimit = [
373 'ORDER BY' => 'rc_timestamp DESC',
374 'LIMIT' => $opts['limit']
375 ];
376 if ( in_array( 'DISTINCT', $query_options ) ) {
377 // ChangeTags::modifyDisplayQuery() adds DISTINCT when filtering on multiple tags.
378 // In order to prevent DISTINCT from causing query performance problems,
379 // we have to GROUP BY the primary key. This in turn requires us to add
380 // the primary key to the end of the ORDER BY, and the old ORDER BY to the
381 // start of the GROUP BY
382 $orderByAndLimit['ORDER BY'] = 'rc_timestamp DESC, rc_id DESC';
383 $orderByAndLimit['GROUP BY'] = 'rc_timestamp, rc_id';
384 }
385 // array_merge() is used intentionally here so that hooks can, should
386 // they so desire, override the ORDER BY / LIMIT condition(s); prior to
387 // MediaWiki 1.26 this used to use the plus operator instead, which meant
388 // that extensions weren't able to change these conditions
389 $query_options = array_merge( $orderByAndLimit, $query_options );
390 $rows = $dbr->select(
391 $tables,
392 $fields,
393 // rc_new is not an ENUM, but adding a redundant rc_new IN (0,1) gives mysql enough
394 // knowledge to use an index merge if it wants (it may use some other index though).
395 $conds + [ 'rc_new' => [ 0, 1 ] ],
396 __METHOD__,
397 $query_options,
398 $join_conds
399 );
400
401 // Build the final data
402 if ( $this->getConfig()->get( 'AllowCategorizedRecentChanges' ) ) {
403 $this->filterByCategories( $rows, $opts );
404 }
405
406 return $rows;
407 }
408
409 protected function runMainQueryHook( &$tables, &$fields, &$conds,
410 &$query_options, &$join_conds, $opts
411 ) {
412 return parent::runMainQueryHook( $tables, $fields, $conds, $query_options, $join_conds, $opts )
413 && Hooks::run(
414 'SpecialRecentChangesQuery',
415 [ &$conds, &$tables, &$join_conds, $opts, &$query_options, &$fields ],
416 '1.23'
417 );
418 }
419
420 protected function getDB() {
421 return wfGetDB( DB_REPLICA, 'recentchanges' );
422 }
423
424 public function outputFeedLinks() {
425 $this->addFeedLinks( $this->getFeedQuery() );
426 }
427
428 /**
429 * Get URL query parameters for action=feedrecentchanges API feed of current recent changes view.
430 *
431 * @return array
432 */
433 protected function getFeedQuery() {
434 $query = array_filter( $this->getOptions()->getAllValues(), function ( $value ) {
435 // API handles empty parameters in a different way
436 return $value !== '';
437 } );
438 $query['action'] = 'feedrecentchanges';
439 $feedLimit = $this->getConfig()->get( 'FeedLimit' );
440 if ( $query['limit'] > $feedLimit ) {
441 $query['limit'] = $feedLimit;
442 }
443
444 return $query;
445 }
446
447 /**
448 * Build and output the actual changes list.
449 *
450 * @param ResultWrapper $rows Database rows
451 * @param FormOptions $opts
452 */
453 public function outputChangesList( $rows, $opts ) {
454 $limit = $opts['limit'];
455
456 $showWatcherCount = $this->getConfig()->get( 'RCShowWatchingUsers' )
457 && $this->getUser()->getOption( 'shownumberswatching' );
458 $watcherCache = [];
459
460 $counter = 1;
461 $list = ChangesList::newFromContext( $this->getContext(), $this->filterGroups );
462 $list->initChangesListRows( $rows );
463
464 $userShowHiddenCats = $this->getUser()->getBoolOption( 'showhiddencats' );
465 $rclistOutput = $list->beginRecentChangesList();
466 if ( $this->isStructuredFilterUiEnabled() ) {
467 $rclistOutput .= $this->makeLegend();
468 }
469
470 foreach ( $rows as $obj ) {
471 if ( $limit == 0 ) {
472 break;
473 }
474 $rc = RecentChange::newFromRow( $obj );
475
476 # Skip CatWatch entries for hidden cats based on user preference
477 if (
478 $rc->getAttribute( 'rc_type' ) == RC_CATEGORIZE &&
479 !$userShowHiddenCats &&
480 $rc->getParam( 'hidden-cat' )
481 ) {
482 continue;
483 }
484
485 $rc->counter = $counter++;
486 # Check if the page has been updated since the last visit
487 if ( $this->getConfig()->get( 'ShowUpdatedMarker' )
488 && !empty( $obj->wl_notificationtimestamp )
489 ) {
490 $rc->notificationtimestamp = ( $obj->rc_timestamp >= $obj->wl_notificationtimestamp );
491 } else {
492 $rc->notificationtimestamp = false; // Default
493 }
494 # Check the number of users watching the page
495 $rc->numberofWatchingusers = 0; // Default
496 if ( $showWatcherCount && $obj->rc_namespace >= 0 ) {
497 if ( !isset( $watcherCache[$obj->rc_namespace][$obj->rc_title] ) ) {
498 $watcherCache[$obj->rc_namespace][$obj->rc_title] =
499 MediaWikiServices::getInstance()->getWatchedItemStore()->countWatchers(
500 new TitleValue( (int)$obj->rc_namespace, $obj->rc_title )
501 );
502 }
503 $rc->numberofWatchingusers = $watcherCache[$obj->rc_namespace][$obj->rc_title];
504 }
505
506 $changeLine = $list->recentChangesLine( $rc, !empty( $obj->wl_user ), $counter );
507 if ( $changeLine !== false ) {
508 $rclistOutput .= $changeLine;
509 --$limit;
510 }
511 }
512 $rclistOutput .= $list->endRecentChangesList();
513
514 if ( $rows->numRows() === 0 ) {
515 $this->outputNoResults();
516 if ( !$this->including() ) {
517 $this->getOutput()->setStatusCode( 404 );
518 }
519 } else {
520 $this->getOutput()->addHTML( $rclistOutput );
521 }
522 }
523
524 /**
525 * Set the text to be displayed above the changes
526 *
527 * @param FormOptions $opts
528 * @param int $numRows Number of rows in the result to show after this header
529 */
530 public function doHeader( $opts, $numRows ) {
531 $this->setTopText( $opts );
532
533 $defaults = $opts->getAllValues();
534 $nondefaults = $opts->getChangedValues();
535
536 $panel = [];
537 if ( !$this->isStructuredFilterUiEnabled() ) {
538 $panel[] = $this->makeLegend();
539 }
540 $panel[] = $this->optionsPanel( $defaults, $nondefaults, $numRows );
541 $panel[] = '<hr />';
542
543 $extraOpts = $this->getExtraOptions( $opts );
544 $extraOptsCount = count( $extraOpts );
545 $count = 0;
546 $submit = ' ' . Xml::submitButton( $this->msg( 'recentchanges-submit' )->text() );
547
548 $out = Xml::openElement( 'table', [ 'class' => 'mw-recentchanges-table' ] );
549 foreach ( $extraOpts as $name => $optionRow ) {
550 # Add submit button to the last row only
551 ++$count;
552 $addSubmit = ( $count === $extraOptsCount ) ? $submit : '';
553
554 $out .= Xml::openElement( 'tr', [ 'class' => $name . 'Form' ] );
555 if ( is_array( $optionRow ) ) {
556 $out .= Xml::tags(
557 'td',
558 [ 'class' => 'mw-label mw-' . $name . '-label' ],
559 $optionRow[0]
560 );
561 $out .= Xml::tags(
562 'td',
563 [ 'class' => 'mw-input' ],
564 $optionRow[1] . $addSubmit
565 );
566 } else {
567 $out .= Xml::tags(
568 'td',
569 [ 'class' => 'mw-input', 'colspan' => 2 ],
570 $optionRow . $addSubmit
571 );
572 }
573 $out .= Xml::closeElement( 'tr' );
574 }
575 $out .= Xml::closeElement( 'table' );
576
577 $unconsumed = $opts->getUnconsumedValues();
578 foreach ( $unconsumed as $key => $value ) {
579 $out .= Html::hidden( $key, $value );
580 }
581
582 $t = $this->getPageTitle();
583 $out .= Html::hidden( 'title', $t->getPrefixedText() );
584 $form = Xml::tags( 'form', [ 'action' => wfScript() ], $out );
585 $panel[] = $form;
586 $panelString = implode( "\n", $panel );
587
588 $rcoptions = Xml::fieldset(
589 $this->msg( 'recentchanges-legend' )->text(),
590 $panelString,
591 [ 'class' => 'rcoptions cloptions' ]
592 );
593
594 // Insert a placeholder for RCFilters
595 if ( $this->isStructuredFilterUiEnabled() ) {
596 $rcfilterContainer = Html::element(
597 'div',
598 [ 'class' => 'rcfilters-container' ]
599 );
600
601 $loadingContainer = Html::rawElement(
602 'div',
603 [ 'class' => 'rcfilters-spinner' ],
604 Html::element(
605 'div',
606 [ 'class' => 'rcfilters-spinner-bounce' ]
607 )
608 );
609
610 // Wrap both with rcfilters-head
611 $this->getOutput()->addHTML(
612 Html::rawElement(
613 'div',
614 [ 'class' => 'rcfilters-head' ],
615 $rcfilterContainer . $rcoptions
616 )
617 );
618
619 // Add spinner
620 $this->getOutput()->addHTML( $loadingContainer );
621 } else {
622 $this->getOutput()->addHTML( $rcoptions );
623 }
624
625 $this->setBottomText( $opts );
626 }
627
628 /**
629 * Send the text to be displayed above the options
630 *
631 * @param FormOptions $opts Unused
632 */
633 function setTopText( FormOptions $opts ) {
634 global $wgContLang;
635
636 $message = $this->msg( 'recentchangestext' )->inContentLanguage();
637 if ( !$message->isDisabled() ) {
638 // Parse the message in this weird ugly way to preserve the ability to include interlanguage
639 // links in it (T172461). In the future when T66969 is resolved, perhaps we can just use
640 // $message->parse() instead. This code is copied from Message::parseText().
641 $parserOutput = MessageCache::singleton()->parse(
642 $message->plain(),
643 $this->getPageTitle(),
644 /*linestart*/true,
645 // Message class sets the interface flag to false when parsing in a language different than
646 // user language, and this is wiki content language
647 /*interface*/false,
648 $wgContLang
649 );
650 $content = $parserOutput->getText();
651 // Add only metadata here (including the language links), text is added below
652 $this->getOutput()->addParserOutputMetadata( $parserOutput );
653
654 $langAttributes = [
655 'lang' => $wgContLang->getHtmlCode(),
656 'dir' => $wgContLang->getDir(),
657 ];
658
659 $topLinksAttributes = [ 'class' => 'mw-recentchanges-toplinks' ];
660
661 if ( $this->isStructuredFilterUiEnabled() ) {
662 $contentTitle = Html::rawElement( 'div',
663 [ 'class' => 'mw-recentchanges-toplinks-title' ],
664 $this->msg( 'rcfilters-other-review-tools' )->parse()
665 );
666 $contentWrapper = Html::rawElement( 'div',
667 array_merge( [ 'class' => 'mw-collapsible-content' ], $langAttributes ),
668 $content
669 );
670 $content = $contentTitle . $contentWrapper;
671 } else {
672 // Language direction should be on the top div only
673 // if the title is not there. If it is there, it's
674 // interface direction, and the language/dir attributes
675 // should be on the content itself
676 $topLinksAttributes = array_merge( $topLinksAttributes, $langAttributes );
677 }
678
679 $this->getOutput()->addHTML(
680 Html::rawElement( 'div', $topLinksAttributes, $content )
681 );
682 }
683 }
684
685 /**
686 * Get options to be displayed in a form
687 *
688 * @param FormOptions $opts
689 * @return array
690 */
691 function getExtraOptions( $opts ) {
692 $opts->consumeValues( [
693 'namespace', 'invert', 'associated', 'tagfilter', 'categories', 'categories_any'
694 ] );
695
696 $extraOpts = [];
697 $extraOpts['namespace'] = $this->namespaceFilterForm( $opts );
698
699 if ( $this->getConfig()->get( 'AllowCategorizedRecentChanges' ) ) {
700 $extraOpts['category'] = $this->categoryFilterForm( $opts );
701 }
702
703 $tagFilter = ChangeTags::buildTagFilterSelector(
704 $opts['tagfilter'], false, $this->getContext() );
705 if ( count( $tagFilter ) ) {
706 $extraOpts['tagfilter'] = $tagFilter;
707 }
708
709 // Don't fire the hook for subclasses. (Or should we?)
710 if ( $this->getName() === 'Recentchanges' ) {
711 Hooks::run( 'SpecialRecentChangesPanel', [ &$extraOpts, $opts ] );
712 }
713
714 return $extraOpts;
715 }
716
717 /**
718 * Add page-specific modules.
719 */
720 protected function addModules() {
721 parent::addModules();
722 $out = $this->getOutput();
723 $out->addModules( 'mediawiki.special.recentchanges' );
724 }
725
726 /**
727 * Get last modified date, for client caching
728 * Don't use this if we are using the patrol feature, patrol changes don't
729 * update the timestamp
730 *
731 * @return string|bool
732 */
733 public function checkLastModified() {
734 $dbr = $this->getDB();
735 $lastmod = $dbr->selectField( 'recentchanges', 'MAX(rc_timestamp)', false, __METHOD__ );
736
737 return $lastmod;
738 }
739
740 /**
741 * Creates the choose namespace selection
742 *
743 * @param FormOptions $opts
744 * @return string
745 */
746 protected function namespaceFilterForm( FormOptions $opts ) {
747 $nsSelect = Html::namespaceSelector(
748 [ 'selected' => $opts['namespace'], 'all' => '' ],
749 [ 'name' => 'namespace', 'id' => 'namespace' ]
750 );
751 $nsLabel = Xml::label( $this->msg( 'namespace' )->text(), 'namespace' );
752 $invert = Xml::checkLabel(
753 $this->msg( 'invert' )->text(), 'invert', 'nsinvert',
754 $opts['invert'],
755 [ 'title' => $this->msg( 'tooltip-invert' )->text() ]
756 );
757 $associated = Xml::checkLabel(
758 $this->msg( 'namespace_association' )->text(), 'associated', 'nsassociated',
759 $opts['associated'],
760 [ 'title' => $this->msg( 'tooltip-namespace_association' )->text() ]
761 );
762
763 return [ $nsLabel, "$nsSelect $invert $associated" ];
764 }
765
766 /**
767 * Create an input to filter changes by categories
768 *
769 * @param FormOptions $opts
770 * @return array
771 */
772 protected function categoryFilterForm( FormOptions $opts ) {
773 list( $label, $input ) = Xml::inputLabelSep( $this->msg( 'rc_categories' )->text(),
774 'categories', 'mw-categories', false, $opts['categories'] );
775
776 $input .= ' ' . Xml::checkLabel( $this->msg( 'rc_categories_any' )->text(),
777 'categories_any', 'mw-categories_any', $opts['categories_any'] );
778
779 return [ $label, $input ];
780 }
781
782 /**
783 * Filter $rows by categories set in $opts
784 *
785 * @param ResultWrapper &$rows Database rows
786 * @param FormOptions $opts
787 */
788 function filterByCategories( &$rows, FormOptions $opts ) {
789 $categories = array_map( 'trim', explode( '|', $opts['categories'] ) );
790
791 if ( !count( $categories ) ) {
792 return;
793 }
794
795 # Filter categories
796 $cats = [];
797 foreach ( $categories as $cat ) {
798 $cat = trim( $cat );
799 if ( $cat == '' ) {
800 continue;
801 }
802 $cats[] = $cat;
803 }
804
805 # Filter articles
806 $articles = [];
807 $a2r = [];
808 $rowsarr = [];
809 foreach ( $rows as $k => $r ) {
810 $nt = Title::makeTitle( $r->rc_namespace, $r->rc_title );
811 $id = $nt->getArticleID();
812 if ( $id == 0 ) {
813 continue; # Page might have been deleted...
814 }
815 if ( !in_array( $id, $articles ) ) {
816 $articles[] = $id;
817 }
818 if ( !isset( $a2r[$id] ) ) {
819 $a2r[$id] = [];
820 }
821 $a2r[$id][] = $k;
822 $rowsarr[$k] = $r;
823 }
824
825 # Shortcut?
826 if ( !count( $articles ) || !count( $cats ) ) {
827 return;
828 }
829
830 # Look up
831 $catFind = new CategoryFinder;
832 $catFind->seed( $articles, $cats, $opts['categories_any'] ? 'OR' : 'AND' );
833 $match = $catFind->run();
834
835 # Filter
836 $newrows = [];
837 foreach ( $match as $id ) {
838 foreach ( $a2r[$id] as $rev ) {
839 $k = $rev;
840 $newrows[$k] = $rowsarr[$k];
841 }
842 }
843 $rows = new FakeResultWrapper( array_values( $newrows ) );
844 }
845
846 /**
847 * Makes change an option link which carries all the other options
848 *
849 * @param string $title Title
850 * @param array $override Options to override
851 * @param array $options Current options
852 * @param bool $active Whether to show the link in bold
853 * @return string
854 */
855 function makeOptionsLink( $title, $override, $options, $active = false ) {
856 $params = $this->convertParamsForLink( $override + $options );
857
858 if ( $active ) {
859 $title = new HtmlArmor( '<strong>' . htmlspecialchars( $title ) . '</strong>' );
860 }
861
862 return $this->getLinkRenderer()->makeKnownLink( $this->getPageTitle(), $title, [
863 'data-params' => json_encode( $override ),
864 'data-keys' => implode( ',', array_keys( $override ) ),
865 ], $params );
866 }
867
868 /**
869 * Creates the options panel.
870 *
871 * @param array $defaults
872 * @param array $nondefaults
873 * @param int $numRows Number of rows in the result to show after this header
874 * @return string
875 */
876 function optionsPanel( $defaults, $nondefaults, $numRows ) {
877 $options = $nondefaults + $defaults;
878
879 $note = '';
880 $msg = $this->msg( 'rclegend' );
881 if ( !$msg->isDisabled() ) {
882 $note .= '<div class="mw-rclegend">' . $msg->parse() . "</div>\n";
883 }
884
885 $lang = $this->getLanguage();
886 $user = $this->getUser();
887 $config = $this->getConfig();
888 if ( $options['from'] ) {
889 $resetLink = $this->makeOptionsLink( $this->msg( 'rclistfromreset' ),
890 [ 'from' => '' ], $nondefaults );
891
892 $noteFromMsg = $this->msg( 'rcnotefrom' )
893 ->numParams( $options['limit'] )
894 ->params(
895 $lang->userTimeAndDate( $options['from'], $user ),
896 $lang->userDate( $options['from'], $user ),
897 $lang->userTime( $options['from'], $user )
898 )
899 ->numParams( $numRows );
900 $note .= Html::rawElement(
901 'span',
902 [ 'class' => 'rcnotefrom' ],
903 $noteFromMsg->parse()
904 ) .
905 ' ' .
906 Html::rawElement(
907 'span',
908 [ 'class' => 'rcoptions-listfromreset' ],
909 $this->msg( 'parentheses' )->rawParams( $resetLink )->parse()
910 ) .
911 '<br />';
912 }
913
914 # Sort data for display and make sure it's unique after we've added user data.
915 $linkLimits = $config->get( 'RCLinkLimits' );
916 $linkLimits[] = $options['limit'];
917 sort( $linkLimits );
918 $linkLimits = array_unique( $linkLimits );
919
920 $linkDays = $config->get( 'RCLinkDays' );
921 $linkDays[] = $options['days'];
922 sort( $linkDays );
923 $linkDays = array_unique( $linkDays );
924
925 // limit links
926 $cl = [];
927 foreach ( $linkLimits as $value ) {
928 $cl[] = $this->makeOptionsLink( $lang->formatNum( $value ),
929 [ 'limit' => $value ], $nondefaults, $value == $options['limit'] );
930 }
931 $cl = $lang->pipeList( $cl );
932
933 // day links, reset 'from' to none
934 $dl = [];
935 foreach ( $linkDays as $value ) {
936 $dl[] = $this->makeOptionsLink( $lang->formatNum( $value ),
937 [ 'days' => $value, 'from' => '' ], $nondefaults, $value == $options['days'] );
938 }
939 $dl = $lang->pipeList( $dl );
940
941 $showhide = [ 'show', 'hide' ];
942
943 $links = [];
944
945 $filterGroups = $this->getFilterGroups();
946
947 foreach ( $filterGroups as $groupName => $group ) {
948 if ( !$group->isPerGroupRequestParameter() ) {
949 foreach ( $group->getFilters() as $key => $filter ) {
950 if ( $filter->displaysOnUnstructuredUi( $this ) ) {
951 $msg = $filter->getShowHide();
952 $linkMessage = $this->msg( $msg . '-' . $showhide[1 - $options[$key]] );
953 // Extensions can define additional filters, but don't need to define the corresponding
954 // messages. If they don't exist, just fall back to 'show' and 'hide'.
955 if ( !$linkMessage->exists() ) {
956 $linkMessage = $this->msg( $showhide[1 - $options[$key]] );
957 }
958
959 $link = $this->makeOptionsLink( $linkMessage->text(),
960 [ $key => 1 - $options[$key] ], $nondefaults );
961
962 $attribs = [
963 'class' => "$msg rcshowhideoption clshowhideoption",
964 'data-filter-name' => $filter->getName(),
965 ];
966
967 if ( $filter->isFeatureAvailableOnStructuredUi( $this ) ) {
968 $attribs['data-feature-in-structured-ui'] = true;
969 }
970
971 $links[] = Html::rawElement(
972 'span',
973 $attribs,
974 $this->msg( $msg )->rawParams( $link )->escaped()
975 );
976 }
977 }
978 }
979 }
980
981 // show from this onward link
982 $timestamp = wfTimestampNow();
983 $now = $lang->userTimeAndDate( $timestamp, $user );
984 $timenow = $lang->userTime( $timestamp, $user );
985 $datenow = $lang->userDate( $timestamp, $user );
986 $pipedLinks = '<span class="rcshowhide">' . $lang->pipeList( $links ) . '</span>';
987
988 $rclinks = '<span class="rclinks">' . $this->msg( 'rclinks' )->rawParams( $cl, $dl, '' )
989 ->parse() . '</span>';
990
991 $rclistfrom = '<span class="rclistfrom">' . $this->makeOptionsLink(
992 $this->msg( 'rclistfrom' )->rawParams( $now, $timenow, $datenow )->parse(),
993 [ 'from' => $timestamp ],
994 $nondefaults
995 ) . '</span>';
996
997 return "{$note}$rclinks<br />$pipedLinks<br />$rclistfrom";
998 }
999
1000 public function isIncludable() {
1001 return true;
1002 }
1003
1004 protected function getCacheTTL() {
1005 return 60 * 5;
1006 }
1007
1008 function getDefaultLimit() {
1009 return $this->getUser()->getIntOption( 'rclimit' );
1010 }
1011
1012 function getDefaultDays() {
1013 return $this->getUser()->getIntOption( 'rcdays' );
1014 }
1015 }