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