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