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