Merge "Remove contentSub from layout when empty"
[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
237 $opts->add( 'days', $this->getDefaultDays(), FormOptions::FLOAT );
238 $opts->add( 'limit', $this->getDefaultLimit() );
239 $opts->add( 'from', '' );
240
241 $opts->add( 'categories', '' );
242 $opts->add( 'categories_any', false );
243
244 return $opts;
245 }
246
247 /**
248 * Get all custom filters
249 *
250 * @return array Map of filter URL param names to properties (msg/default)
251 */
252 protected function getCustomFilters() {
253 if ( $this->customFilters === null ) {
254 $this->customFilters = parent::getCustomFilters();
255 Hooks::run( 'SpecialRecentChangesFilters', [ $this, &$this->customFilters ], '1.23' );
256 }
257
258 return $this->customFilters;
259 }
260
261 /**
262 * Process $par and put options found in $opts. Used when including the page.
263 *
264 * @param string $par
265 * @param FormOptions $opts
266 */
267 public function parseParameters( $par, FormOptions $opts ) {
268 parent::parseParameters( $par, $opts );
269
270 $bits = preg_split( '/\s*,\s*/', trim( $par ) );
271 foreach ( $bits as $bit ) {
272 if ( is_numeric( $bit ) ) {
273 $opts['limit'] = $bit;
274 }
275
276 $m = [];
277 if ( preg_match( '/^limit=(\d+)$/', $bit, $m ) ) {
278 $opts['limit'] = $m[1];
279 }
280 if ( preg_match( '/^days=(\d+(?:\.\d+)?)$/', $bit, $m ) ) {
281 $opts['days'] = $m[1];
282 }
283 if ( preg_match( '/^namespace=(.*)$/', $bit, $m ) ) {
284 $opts['namespace'] = $m[1];
285 }
286 if ( preg_match( '/^tagfilter=(.*)$/', $bit, $m ) ) {
287 $opts['tagfilter'] = $m[1];
288 }
289 }
290 }
291
292 public function validateOptions( FormOptions $opts ) {
293 $opts->validateIntBounds( 'limit', 0, 5000 );
294 $opts->validateBounds( 'days', 0, $this->getConfig()->get( 'RCMaxAge' ) / ( 3600 * 24 ) );
295 parent::validateOptions( $opts );
296 }
297
298 /**
299 * @inheritDoc
300 */
301 protected function buildQuery( &$tables, &$fields, &$conds,
302 &$query_options, &$join_conds, FormOptions $opts
303 ) {
304 $dbr = $this->getDB();
305 parent::buildQuery( $tables, $fields, $conds,
306 $query_options, $join_conds, $opts );
307
308 // Calculate cutoff
309 $cutoff_unixtime = time() - $opts['days'] * 3600 * 24;
310 $cutoff = $dbr->timestamp( $cutoff_unixtime );
311
312 $fromValid = preg_match( '/^[0-9]{14}$/', $opts['from'] );
313 if ( $fromValid && $opts['from'] > wfTimestamp( TS_MW, $cutoff ) ) {
314 $cutoff = $dbr->timestamp( $opts['from'] );
315 } else {
316 $opts->reset( 'from' );
317 }
318
319 $conds[] = 'rc_timestamp >= ' . $dbr->addQuotes( $cutoff );
320 }
321
322 /**
323 * @inheritDoc
324 */
325 protected function doMainQuery( $tables, $fields, $conds, $query_options,
326 $join_conds, FormOptions $opts
327 ) {
328 $dbr = $this->getDB();
329 $user = $this->getUser();
330
331 $tables[] = 'recentchanges';
332 $fields = array_merge( RecentChange::selectFields(), $fields );
333
334 // JOIN on watchlist for users
335 if ( $user->isLoggedIn() && $user->isAllowed( 'viewmywatchlist' ) ) {
336 $tables[] = 'watchlist';
337 $fields[] = 'wl_user';
338 $fields[] = 'wl_notificationtimestamp';
339 $join_conds['watchlist'] = [ 'LEFT JOIN', [
340 'wl_user' => $user->getId(),
341 'wl_title=rc_title',
342 'wl_namespace=rc_namespace'
343 ] ];
344 }
345
346 // JOIN on page, used for 'last revision' filter highlight
347 $tables[] = 'page';
348 $fields[] = 'page_latest';
349 $join_conds['page'] = [ 'LEFT JOIN', 'rc_cur_id=page_id' ];
350
351 $tagFilter = $opts['tagfilter'] ? explode( '|', $opts['tagfilter'] ) : [];
352 ChangeTags::modifyDisplayQuery(
353 $tables,
354 $fields,
355 $conds,
356 $join_conds,
357 $query_options,
358 $tagFilter
359 );
360
361 if ( !$this->runMainQueryHook( $tables, $fields, $conds, $query_options, $join_conds,
362 $opts )
363 ) {
364 return false;
365 }
366
367 if ( $this->areFiltersInConflict() ) {
368 return false;
369 }
370
371 $orderByAndLimit = [
372 'ORDER BY' => 'rc_timestamp DESC',
373 'LIMIT' => $opts['limit']
374 ];
375 if ( in_array( 'DISTINCT', $query_options ) ) {
376 // ChangeTags::modifyDisplayQuery() adds DISTINCT when filtering on multiple tags.
377 // In order to prevent DISTINCT from causing query performance problems,
378 // we have to GROUP BY the primary key. This in turn requires us to add
379 // the primary key to the end of the ORDER BY, and the old ORDER BY to the
380 // start of the GROUP BY
381 $orderByAndLimit['ORDER BY'] = 'rc_timestamp DESC, rc_id DESC';
382 $orderByAndLimit['GROUP BY'] = 'rc_timestamp, rc_id';
383 }
384 // array_merge() is used intentionally here so that hooks can, should
385 // they so desire, override the ORDER BY / LIMIT condition(s); prior to
386 // MediaWiki 1.26 this used to use the plus operator instead, which meant
387 // that extensions weren't able to change these conditions
388 $query_options = array_merge( $orderByAndLimit, $query_options );
389 $rows = $dbr->select(
390 $tables,
391 $fields,
392 // rc_new is not an ENUM, but adding a redundant rc_new IN (0,1) gives mysql enough
393 // knowledge to use an index merge if it wants (it may use some other index though).
394 $conds + [ 'rc_new' => [ 0, 1 ] ],
395 __METHOD__,
396 $query_options,
397 $join_conds
398 );
399
400 // Build the final data
401 if ( $this->getConfig()->get( 'AllowCategorizedRecentChanges' ) ) {
402 $this->filterByCategories( $rows, $opts );
403 }
404
405 return $rows;
406 }
407
408 protected function runMainQueryHook( &$tables, &$fields, &$conds,
409 &$query_options, &$join_conds, $opts
410 ) {
411 return parent::runMainQueryHook( $tables, $fields, $conds, $query_options, $join_conds, $opts )
412 && Hooks::run(
413 'SpecialRecentChangesQuery',
414 [ &$conds, &$tables, &$join_conds, $opts, &$query_options, &$fields ],
415 '1.23'
416 );
417 }
418
419 protected function getDB() {
420 return wfGetDB( DB_REPLICA, 'recentchanges' );
421 }
422
423 public function outputFeedLinks() {
424 $this->addFeedLinks( $this->getFeedQuery() );
425 }
426
427 /**
428 * Get URL query parameters for action=feedrecentchanges API feed of current recent changes view.
429 *
430 * @return array
431 */
432 protected function getFeedQuery() {
433 $query = array_filter( $this->getOptions()->getAllValues(), function ( $value ) {
434 // API handles empty parameters in a different way
435 return $value !== '';
436 } );
437 $query['action'] = 'feedrecentchanges';
438 $feedLimit = $this->getConfig()->get( 'FeedLimit' );
439 if ( $query['limit'] > $feedLimit ) {
440 $query['limit'] = $feedLimit;
441 }
442
443 return $query;
444 }
445
446 /**
447 * Build and output the actual changes list.
448 *
449 * @param ResultWrapper $rows Database rows
450 * @param FormOptions $opts
451 */
452 public function outputChangesList( $rows, $opts ) {
453 $limit = $opts['limit'];
454
455 $showWatcherCount = $this->getConfig()->get( 'RCShowWatchingUsers' )
456 && $this->getUser()->getOption( 'shownumberswatching' );
457 $watcherCache = [];
458
459 $counter = 1;
460 $list = ChangesList::newFromContext( $this->getContext(), $this->filterGroups );
461 $list->initChangesListRows( $rows );
462
463 $userShowHiddenCats = $this->getUser()->getBoolOption( 'showhiddencats' );
464 $rclistOutput = $list->beginRecentChangesList();
465 if ( $this->isStructuredFilterUiEnabled() ) {
466 $rclistOutput .= $this->makeLegend();
467 }
468
469 foreach ( $rows as $obj ) {
470 if ( $limit == 0 ) {
471 break;
472 }
473 $rc = RecentChange::newFromRow( $obj );
474
475 # Skip CatWatch entries for hidden cats based on user preference
476 if (
477 $rc->getAttribute( 'rc_type' ) == RC_CATEGORIZE &&
478 !$userShowHiddenCats &&
479 $rc->getParam( 'hidden-cat' )
480 ) {
481 continue;
482 }
483
484 $rc->counter = $counter++;
485 # Check if the page has been updated since the last visit
486 if ( $this->getConfig()->get( 'ShowUpdatedMarker' )
487 && !empty( $obj->wl_notificationtimestamp )
488 ) {
489 $rc->notificationtimestamp = ( $obj->rc_timestamp >= $obj->wl_notificationtimestamp );
490 } else {
491 $rc->notificationtimestamp = false; // Default
492 }
493 # Check the number of users watching the page
494 $rc->numberofWatchingusers = 0; // Default
495 if ( $showWatcherCount && $obj->rc_namespace >= 0 ) {
496 if ( !isset( $watcherCache[$obj->rc_namespace][$obj->rc_title] ) ) {
497 $watcherCache[$obj->rc_namespace][$obj->rc_title] =
498 MediaWikiServices::getInstance()->getWatchedItemStore()->countWatchers(
499 new TitleValue( (int)$obj->rc_namespace, $obj->rc_title )
500 );
501 }
502 $rc->numberofWatchingusers = $watcherCache[$obj->rc_namespace][$obj->rc_title];
503 }
504
505 $changeLine = $list->recentChangesLine( $rc, !empty( $obj->wl_user ), $counter );
506 if ( $changeLine !== false ) {
507 $rclistOutput .= $changeLine;
508 --$limit;
509 }
510 }
511 $rclistOutput .= $list->endRecentChangesList();
512
513 if ( $rows->numRows() === 0 ) {
514 $this->outputNoResults();
515 if ( !$this->including() ) {
516 $this->getOutput()->setStatusCode( 404 );
517 }
518 } else {
519 $this->getOutput()->addHTML( $rclistOutput );
520 }
521 }
522
523 /**
524 * Set the text to be displayed above the changes
525 *
526 * @param FormOptions $opts
527 * @param int $numRows Number of rows in the result to show after this header
528 */
529 public function doHeader( $opts, $numRows ) {
530 $this->setTopText( $opts );
531
532 $defaults = $opts->getAllValues();
533 $nondefaults = $opts->getChangedValues();
534
535 $panel = [];
536 if ( !$this->isStructuredFilterUiEnabled() ) {
537 $panel[] = $this->makeLegend();
538 }
539 $panel[] = $this->optionsPanel( $defaults, $nondefaults, $numRows );
540 $panel[] = '<hr />';
541
542 $extraOpts = $this->getExtraOptions( $opts );
543 $extraOptsCount = count( $extraOpts );
544 $count = 0;
545 $submit = ' ' . Xml::submitButton( $this->msg( 'recentchanges-submit' )->text() );
546
547 $out = Xml::openElement( 'table', [ 'class' => 'mw-recentchanges-table' ] );
548 foreach ( $extraOpts as $name => $optionRow ) {
549 # Add submit button to the last row only
550 ++$count;
551 $addSubmit = ( $count === $extraOptsCount ) ? $submit : '';
552
553 $out .= Xml::openElement( 'tr', [ 'class' => $name . 'Form' ] );
554 if ( is_array( $optionRow ) ) {
555 $out .= Xml::tags(
556 'td',
557 [ 'class' => 'mw-label mw-' . $name . '-label' ],
558 $optionRow[0]
559 );
560 $out .= Xml::tags(
561 'td',
562 [ 'class' => 'mw-input' ],
563 $optionRow[1] . $addSubmit
564 );
565 } else {
566 $out .= Xml::tags(
567 'td',
568 [ 'class' => 'mw-input', 'colspan' => 2 ],
569 $optionRow . $addSubmit
570 );
571 }
572 $out .= Xml::closeElement( 'tr' );
573 }
574 $out .= Xml::closeElement( 'table' );
575
576 $unconsumed = $opts->getUnconsumedValues();
577 foreach ( $unconsumed as $key => $value ) {
578 $out .= Html::hidden( $key, $value );
579 }
580
581 $t = $this->getPageTitle();
582 $out .= Html::hidden( 'title', $t->getPrefixedText() );
583 $form = Xml::tags( 'form', [ 'action' => wfScript() ], $out );
584 $panel[] = $form;
585 $panelString = implode( "\n", $panel );
586
587 $rcoptions = Xml::fieldset(
588 $this->msg( 'recentchanges-legend' )->text(),
589 $panelString,
590 [ 'class' => 'rcoptions cloptions' ]
591 );
592
593 // Insert a placeholder for RCFilters
594 if ( $this->isStructuredFilterUiEnabled() ) {
595 $rcfilterContainer = Html::element(
596 'div',
597 [ 'class' => 'rcfilters-container' ]
598 );
599
600 $loadingContainer = Html::rawElement(
601 'div',
602 [ 'class' => 'rcfilters-spinner' ],
603 Html::element(
604 'div',
605 [ 'class' => 'rcfilters-spinner-bounce' ]
606 )
607 );
608
609 // Wrap both with rcfilters-head
610 $this->getOutput()->addHTML(
611 Html::rawElement(
612 'div',
613 [ 'class' => 'rcfilters-head' ],
614 $rcfilterContainer . $rcoptions
615 )
616 );
617
618 // Add spinner
619 $this->getOutput()->addHTML( $loadingContainer );
620 } else {
621 $this->getOutput()->addHTML( $rcoptions );
622 }
623
624 $this->setBottomText( $opts );
625 }
626
627 /**
628 * Send the text to be displayed above the options
629 *
630 * @param FormOptions $opts Unused
631 */
632 function setTopText( FormOptions $opts ) {
633 global $wgContLang;
634
635 $message = $this->msg( 'recentchangestext' )->inContentLanguage();
636 if ( !$message->isDisabled() ) {
637 // Parse the message in this weird ugly way to preserve the ability to include interlanguage
638 // links in it (T172461). In the future when T66969 is resolved, perhaps we can just use
639 // $message->parse() instead. This code is copied from Message::parseText().
640 $parserOutput = MessageCache::singleton()->parse(
641 $message->plain(),
642 $this->getPageTitle(),
643 /*linestart*/true,
644 // Message class sets the interface flag to false when parsing in a language different than
645 // user language, and this is wiki content language
646 /*interface*/false,
647 $wgContLang
648 );
649 $content = $parserOutput->getText();
650 // Add only metadata here (including the language links), text is added below
651 $this->getOutput()->addParserOutputMetadata( $parserOutput );
652
653 $langAttributes = [
654 'lang' => $wgContLang->getHtmlCode(),
655 'dir' => $wgContLang->getDir(),
656 ];
657
658 $topLinksAttributes = [ 'class' => 'mw-recentchanges-toplinks' ];
659
660 if ( $this->isStructuredFilterUiEnabled() ) {
661 $contentTitle = Html::rawElement( 'div',
662 [ 'class' => 'mw-recentchanges-toplinks-title' ],
663 $this->msg( 'rcfilters-other-review-tools' )->parse()
664 );
665 $contentWrapper = Html::rawElement( 'div',
666 array_merge( [ 'class' => 'mw-collapsible-content' ], $langAttributes ),
667 $content
668 );
669 $content = $contentTitle . $contentWrapper;
670 } else {
671 // Language direction should be on the top div only
672 // if the title is not there. If it is there, it's
673 // interface direction, and the language/dir attributes
674 // should be on the content itself
675 $topLinksAttributes = array_merge( $topLinksAttributes, $langAttributes );
676 }
677
678 $this->getOutput()->addHTML(
679 Html::rawElement( 'div', $topLinksAttributes, $content )
680 );
681 }
682 }
683
684 /**
685 * Get options to be displayed in a form
686 *
687 * @param FormOptions $opts
688 * @return array
689 */
690 function getExtraOptions( $opts ) {
691 $opts->consumeValues( [
692 'namespace', 'invert', 'associated', 'tagfilter', 'categories', 'categories_any'
693 ] );
694
695 $extraOpts = [];
696 $extraOpts['namespace'] = $this->namespaceFilterForm( $opts );
697
698 if ( $this->getConfig()->get( 'AllowCategorizedRecentChanges' ) ) {
699 $extraOpts['category'] = $this->categoryFilterForm( $opts );
700 }
701
702 $tagFilter = ChangeTags::buildTagFilterSelector(
703 $opts['tagfilter'], false, $this->getContext() );
704 if ( count( $tagFilter ) ) {
705 $extraOpts['tagfilter'] = $tagFilter;
706 }
707
708 // Don't fire the hook for subclasses. (Or should we?)
709 if ( $this->getName() === 'Recentchanges' ) {
710 Hooks::run( 'SpecialRecentChangesPanel', [ &$extraOpts, $opts ] );
711 }
712
713 return $extraOpts;
714 }
715
716 /**
717 * Add page-specific modules.
718 */
719 protected function addModules() {
720 parent::addModules();
721 $out = $this->getOutput();
722 $out->addModules( 'mediawiki.special.recentchanges' );
723 }
724
725 /**
726 * Get last modified date, for client caching
727 * Don't use this if we are using the patrol feature, patrol changes don't
728 * update the timestamp
729 *
730 * @return string|bool
731 */
732 public function checkLastModified() {
733 $dbr = $this->getDB();
734 $lastmod = $dbr->selectField( 'recentchanges', 'MAX(rc_timestamp)', false, __METHOD__ );
735
736 return $lastmod;
737 }
738
739 /**
740 * Creates the choose namespace selection
741 *
742 * @param FormOptions $opts
743 * @return string
744 */
745 protected function namespaceFilterForm( FormOptions $opts ) {
746 $nsSelect = Html::namespaceSelector(
747 [ 'selected' => $opts['namespace'], 'all' => '' ],
748 [ 'name' => 'namespace', 'id' => 'namespace' ]
749 );
750 $nsLabel = Xml::label( $this->msg( 'namespace' )->text(), 'namespace' );
751 $invert = Xml::checkLabel(
752 $this->msg( 'invert' )->text(), 'invert', 'nsinvert',
753 $opts['invert'],
754 [ 'title' => $this->msg( 'tooltip-invert' )->text() ]
755 );
756 $associated = Xml::checkLabel(
757 $this->msg( 'namespace_association' )->text(), 'associated', 'nsassociated',
758 $opts['associated'],
759 [ 'title' => $this->msg( 'tooltip-namespace_association' )->text() ]
760 );
761
762 return [ $nsLabel, "$nsSelect $invert $associated" ];
763 }
764
765 /**
766 * Create an input to filter changes by categories
767 *
768 * @param FormOptions $opts
769 * @return array
770 */
771 protected function categoryFilterForm( FormOptions $opts ) {
772 list( $label, $input ) = Xml::inputLabelSep( $this->msg( 'rc_categories' )->text(),
773 'categories', 'mw-categories', false, $opts['categories'] );
774
775 $input .= ' ' . Xml::checkLabel( $this->msg( 'rc_categories_any' )->text(),
776 'categories_any', 'mw-categories_any', $opts['categories_any'] );
777
778 return [ $label, $input ];
779 }
780
781 /**
782 * Filter $rows by categories set in $opts
783 *
784 * @param ResultWrapper &$rows Database rows
785 * @param FormOptions $opts
786 */
787 function filterByCategories( &$rows, FormOptions $opts ) {
788 $categories = array_map( 'trim', explode( '|', $opts['categories'] ) );
789
790 if ( !count( $categories ) ) {
791 return;
792 }
793
794 # Filter categories
795 $cats = [];
796 foreach ( $categories as $cat ) {
797 $cat = trim( $cat );
798 if ( $cat == '' ) {
799 continue;
800 }
801 $cats[] = $cat;
802 }
803
804 # Filter articles
805 $articles = [];
806 $a2r = [];
807 $rowsarr = [];
808 foreach ( $rows as $k => $r ) {
809 $nt = Title::makeTitle( $r->rc_namespace, $r->rc_title );
810 $id = $nt->getArticleID();
811 if ( $id == 0 ) {
812 continue; # Page might have been deleted...
813 }
814 if ( !in_array( $id, $articles ) ) {
815 $articles[] = $id;
816 }
817 if ( !isset( $a2r[$id] ) ) {
818 $a2r[$id] = [];
819 }
820 $a2r[$id][] = $k;
821 $rowsarr[$k] = $r;
822 }
823
824 # Shortcut?
825 if ( !count( $articles ) || !count( $cats ) ) {
826 return;
827 }
828
829 # Look up
830 $catFind = new CategoryFinder;
831 $catFind->seed( $articles, $cats, $opts['categories_any'] ? 'OR' : 'AND' );
832 $match = $catFind->run();
833
834 # Filter
835 $newrows = [];
836 foreach ( $match as $id ) {
837 foreach ( $a2r[$id] as $rev ) {
838 $k = $rev;
839 $newrows[$k] = $rowsarr[$k];
840 }
841 }
842 $rows = new FakeResultWrapper( array_values( $newrows ) );
843 }
844
845 /**
846 * Makes change an option link which carries all the other options
847 *
848 * @param string $title Title
849 * @param array $override Options to override
850 * @param array $options Current options
851 * @param bool $active Whether to show the link in bold
852 * @return string
853 */
854 function makeOptionsLink( $title, $override, $options, $active = false ) {
855 $params = $this->convertParamsForLink( $override + $options );
856
857 if ( $active ) {
858 $title = new HtmlArmor( '<strong>' . htmlspecialchars( $title ) . '</strong>' );
859 }
860
861 return $this->getLinkRenderer()->makeKnownLink( $this->getPageTitle(), $title, [
862 'data-params' => json_encode( $override ),
863 'data-keys' => implode( ',', array_keys( $override ) ),
864 ], $params );
865 }
866
867 /**
868 * Creates the options panel.
869 *
870 * @param array $defaults
871 * @param array $nondefaults
872 * @param int $numRows Number of rows in the result to show after this header
873 * @return string
874 */
875 function optionsPanel( $defaults, $nondefaults, $numRows ) {
876 $options = $nondefaults + $defaults;
877
878 $note = '';
879 $msg = $this->msg( 'rclegend' );
880 if ( !$msg->isDisabled() ) {
881 $note .= '<div class="mw-rclegend">' . $msg->parse() . "</div>\n";
882 }
883
884 $lang = $this->getLanguage();
885 $user = $this->getUser();
886 $config = $this->getConfig();
887 if ( $options['from'] ) {
888 $resetLink = $this->makeOptionsLink( $this->msg( 'rclistfromreset' ),
889 [ 'from' => '' ], $nondefaults );
890
891 $noteFromMsg = $this->msg( 'rcnotefrom' )
892 ->numParams( $options['limit'] )
893 ->params(
894 $lang->userTimeAndDate( $options['from'], $user ),
895 $lang->userDate( $options['from'], $user ),
896 $lang->userTime( $options['from'], $user )
897 )
898 ->numParams( $numRows );
899 $note .= Html::rawElement(
900 'span',
901 [ 'class' => 'rcnotefrom' ],
902 $noteFromMsg->parse()
903 ) .
904 ' ' .
905 Html::rawElement(
906 'span',
907 [ 'class' => 'rcoptions-listfromreset' ],
908 $this->msg( 'parentheses' )->rawParams( $resetLink )->parse()
909 ) .
910 '<br />';
911 }
912
913 # Sort data for display and make sure it's unique after we've added user data.
914 $linkLimits = $config->get( 'RCLinkLimits' );
915 $linkLimits[] = $options['limit'];
916 sort( $linkLimits );
917 $linkLimits = array_unique( $linkLimits );
918
919 $linkDays = $config->get( 'RCLinkDays' );
920 $linkDays[] = $options['days'];
921 sort( $linkDays );
922 $linkDays = array_unique( $linkDays );
923
924 // limit links
925 $cl = [];
926 foreach ( $linkLimits as $value ) {
927 $cl[] = $this->makeOptionsLink( $lang->formatNum( $value ),
928 [ 'limit' => $value ], $nondefaults, $value == $options['limit'] );
929 }
930 $cl = $lang->pipeList( $cl );
931
932 // day links, reset 'from' to none
933 $dl = [];
934 foreach ( $linkDays as $value ) {
935 $dl[] = $this->makeOptionsLink( $lang->formatNum( $value ),
936 [ 'days' => $value, 'from' => '' ], $nondefaults, $value == $options['days'] );
937 }
938 $dl = $lang->pipeList( $dl );
939
940 $showhide = [ 'show', 'hide' ];
941
942 $links = [];
943
944 $filterGroups = $this->getFilterGroups();
945
946 foreach ( $filterGroups as $groupName => $group ) {
947 if ( !$group->isPerGroupRequestParameter() ) {
948 foreach ( $group->getFilters() as $key => $filter ) {
949 if ( $filter->displaysOnUnstructuredUi( $this ) ) {
950 $msg = $filter->getShowHide();
951 $linkMessage = $this->msg( $msg . '-' . $showhide[1 - $options[$key]] );
952 // Extensions can define additional filters, but don't need to define the corresponding
953 // messages. If they don't exist, just fall back to 'show' and 'hide'.
954 if ( !$linkMessage->exists() ) {
955 $linkMessage = $this->msg( $showhide[1 - $options[$key]] );
956 }
957
958 $link = $this->makeOptionsLink( $linkMessage->text(),
959 [ $key => 1 - $options[$key] ], $nondefaults );
960
961 $attribs = [
962 'class' => "$msg rcshowhideoption clshowhideoption",
963 'data-filter-name' => $filter->getName(),
964 ];
965
966 if ( $filter->isFeatureAvailableOnStructuredUi( $this ) ) {
967 $attribs['data-feature-in-structured-ui'] = true;
968 }
969
970 $links[] = Html::rawElement(
971 'span',
972 $attribs,
973 $this->msg( $msg )->rawParams( $link )->escaped()
974 );
975 }
976 }
977 }
978 }
979
980 // show from this onward link
981 $timestamp = wfTimestampNow();
982 $now = $lang->userTimeAndDate( $timestamp, $user );
983 $timenow = $lang->userTime( $timestamp, $user );
984 $datenow = $lang->userDate( $timestamp, $user );
985 $pipedLinks = '<span class="rcshowhide">' . $lang->pipeList( $links ) . '</span>';
986
987 $rclinks = '<span class="rclinks">' . $this->msg( 'rclinks' )->rawParams( $cl, $dl, '' )
988 ->parse() . '</span>';
989
990 $rclistfrom = '<span class="rclistfrom">' . $this->makeOptionsLink(
991 $this->msg( 'rclistfrom' )->rawParams( $now, $timenow, $datenow )->parse(),
992 [ 'from' => $timestamp ],
993 $nondefaults
994 ) . '</span>';
995
996 return "{$note}$rclinks<br />$pipedLinks<br />$rclistfrom";
997 }
998
999 public function isIncludable() {
1000 return true;
1001 }
1002
1003 protected function getCacheTTL() {
1004 return 60 * 5;
1005 }
1006
1007 function getDefaultLimit() {
1008 return $this->getUser()->getIntOption( 'rclimit' );
1009 }
1010
1011 function getDefaultDays() {
1012 return floatval( $this->getUser()->getOption( 'rcdays' ) );
1013 }
1014 }