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