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