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