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