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