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