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