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