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