85ac2de68022b884ac6aec056c1b3b8da0884387
[lhc/web/wiklou.git] / includes / specials / SpecialWatchlist.php
1 <?php
2 /**
3 * Implements Special:Watchlist
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
26 /**
27 * A special page that lists last changes made to the wiki,
28 * limited to user-defined list of titles.
29 *
30 * @ingroup SpecialPage
31 */
32 class SpecialWatchlist extends ChangesListSpecialPage {
33 public function __construct( $page = 'Watchlist', $restriction = 'viewmywatchlist' ) {
34 parent::__construct( $page, $restriction );
35 }
36
37 public function doesWrites() {
38 return true;
39 }
40
41 /**
42 * Main execution point
43 *
44 * @param string $subpage
45 */
46 function execute( $subpage ) {
47 // Anons don't get a watchlist
48 $this->requireLogin( 'watchlistanontext' );
49
50 $output = $this->getOutput();
51 $request = $this->getRequest();
52 $this->addHelpLink( 'Help:Watching pages' );
53 $output->addModules( [
54 'mediawiki.special.changeslist.visitedstatus',
55 'mediawiki.special.watchlist',
56 ] );
57
58 $mode = SpecialEditWatchlist::getMode( $request, $subpage );
59 if ( $mode !== false ) {
60 if ( $mode === SpecialEditWatchlist::EDIT_RAW ) {
61 $title = SpecialPage::getTitleFor( 'EditWatchlist', 'raw' );
62 } elseif ( $mode === SpecialEditWatchlist::EDIT_CLEAR ) {
63 $title = SpecialPage::getTitleFor( 'EditWatchlist', 'clear' );
64 } else {
65 $title = SpecialPage::getTitleFor( 'EditWatchlist' );
66 }
67
68 $output->redirect( $title->getLocalURL() );
69
70 return;
71 }
72
73 $this->checkPermissions();
74
75 $user = $this->getUser();
76 $opts = $this->getOptions();
77
78 $config = $this->getConfig();
79 if ( ( $config->get( 'EnotifWatchlist' ) || $config->get( 'ShowUpdatedMarker' ) )
80 && $request->getVal( 'reset' )
81 && $request->wasPosted()
82 ) {
83 $user->clearAllNotifications();
84 $output->redirect( $this->getPageTitle()->getFullURL( $opts->getChangedValues() ) );
85
86 return;
87 }
88
89 parent::execute( $subpage );
90 }
91
92 /**
93 * Return an array of subpages that this special page will accept.
94 *
95 * @see also SpecialEditWatchlist::getSubpagesForPrefixSearch
96 * @return string[] subpages
97 */
98 public function getSubpagesForPrefixSearch() {
99 return [
100 'clear',
101 'edit',
102 'raw',
103 ];
104 }
105
106 /**
107 * Get a FormOptions object containing the default options
108 *
109 * @return FormOptions
110 */
111 public function getDefaultOptions() {
112 $opts = parent::getDefaultOptions();
113 $user = $this->getUser();
114
115 $opts->add( 'days', $user->getOption( 'watchlistdays' ), FormOptions::FLOAT );
116 $opts->add( 'extended', $user->getBoolOption( 'extendwatchlist' ) );
117 if ( $this->getRequest()->getVal( 'action' ) == 'submit' ) {
118 // The user has submitted the form, so we dont need the default values
119 return $opts;
120 }
121
122 $opts->add( 'hideminor', $user->getBoolOption( 'watchlisthideminor' ) );
123 $opts->add( 'hidebots', $user->getBoolOption( 'watchlisthidebots' ) );
124 $opts->add( 'hideanons', $user->getBoolOption( 'watchlisthideanons' ) );
125 $opts->add( 'hideliu', $user->getBoolOption( 'watchlisthideliu' ) );
126 $opts->add( 'hidepatrolled', $user->getBoolOption( 'watchlisthidepatrolled' ) );
127 $opts->add( 'hidemyself', $user->getBoolOption( 'watchlisthideown' ) );
128 $opts->add( 'hidecategorization', $user->getBoolOption( 'watchlisthidecategorization' ) );
129
130 return $opts;
131 }
132
133 /**
134 * Get all custom filters
135 *
136 * @return array Map of filter URL param names to properties (msg/default)
137 */
138 protected function getCustomFilters() {
139 if ( $this->customFilters === null ) {
140 $this->customFilters = parent::getCustomFilters();
141 Hooks::run( 'SpecialWatchlistFilters', [ $this, &$this->customFilters ], '1.23' );
142 }
143
144 return $this->customFilters;
145 }
146
147 /**
148 * Fetch values for a FormOptions object from the WebRequest associated with this instance.
149 *
150 * Maps old pre-1.23 request parameters Watchlist used to use (different from Recentchanges' ones)
151 * to the current ones.
152 *
153 * @param FormOptions $opts
154 * @return FormOptions
155 */
156 protected function fetchOptionsFromRequest( $opts ) {
157 static $compatibilityMap = [
158 'hideMinor' => 'hideminor',
159 'hideBots' => 'hidebots',
160 'hideAnons' => 'hideanons',
161 'hideLiu' => 'hideliu',
162 'hidePatrolled' => 'hidepatrolled',
163 'hideOwn' => 'hidemyself',
164 ];
165
166 $params = $this->getRequest()->getValues();
167 foreach ( $compatibilityMap as $from => $to ) {
168 if ( isset( $params[$from] ) ) {
169 $params[$to] = $params[$from];
170 unset( $params[$from] );
171 }
172 }
173
174 // Not the prettiest way to achieve this… FormOptions internally depends on data sanitization
175 // methods defined on WebRequest and removing this dependency would cause some code duplication.
176 $request = new DerivativeRequest( $this->getRequest(), $params );
177 $opts->fetchValuesFromRequest( $request );
178
179 return $opts;
180 }
181
182 /**
183 * Return an array of conditions depending of options set in $opts
184 *
185 * @param FormOptions $opts
186 * @return array
187 */
188 public function buildMainQueryConds( FormOptions $opts ) {
189 $dbr = $this->getDB();
190 $conds = parent::buildMainQueryConds( $opts );
191
192 // Calculate cutoff
193 if ( $opts['days'] > 0 ) {
194 $conds[] = 'rc_timestamp > ' .
195 $dbr->addQuotes( $dbr->timestamp( time() - intval( $opts['days'] * 86400 ) ) );
196 }
197
198 return $conds;
199 }
200
201 /**
202 * Process the query
203 *
204 * @param array $conds
205 * @param FormOptions $opts
206 * @return bool|ResultWrapper Result or false (for Recentchangeslinked only)
207 */
208 public function doMainQuery( $conds, $opts ) {
209 $dbr = $this->getDB();
210 $user = $this->getUser();
211
212 # Toggle watchlist content (all recent edits or just the latest)
213 if ( $opts['extended'] ) {
214 $limitWatchlist = $user->getIntOption( 'wllimit' );
215 $usePage = false;
216 } else {
217 # Top log Ids for a page are not stored
218 $nonRevisionTypes = [ RC_LOG ];
219 Hooks::run( 'SpecialWatchlistGetNonRevisionTypes', [ &$nonRevisionTypes ] );
220 if ( $nonRevisionTypes ) {
221 $conds[] = $dbr->makeList(
222 [
223 'rc_this_oldid=page_latest',
224 'rc_type' => $nonRevisionTypes,
225 ],
226 LIST_OR
227 );
228 }
229 $limitWatchlist = 0;
230 $usePage = true;
231 }
232
233 $tables = [ 'recentchanges', 'watchlist' ];
234 $fields = RecentChange::selectFields();
235 $query_options = [ 'ORDER BY' => 'rc_timestamp DESC' ];
236 $join_conds = [
237 'watchlist' => [
238 'INNER JOIN',
239 [
240 'wl_user' => $user->getId(),
241 'wl_namespace=rc_namespace',
242 'wl_title=rc_title'
243 ],
244 ],
245 ];
246
247 if ( $this->getConfig()->get( 'ShowUpdatedMarker' ) ) {
248 $fields[] = 'wl_notificationtimestamp';
249 }
250 if ( $limitWatchlist ) {
251 $query_options['LIMIT'] = $limitWatchlist;
252 }
253
254 $rollbacker = $user->isAllowed( 'rollback' );
255 if ( $usePage || $rollbacker ) {
256 $tables[] = 'page';
257 $join_conds['page'] = [ 'LEFT JOIN', 'rc_cur_id=page_id' ];
258 if ( $rollbacker ) {
259 $fields[] = 'page_latest';
260 }
261 }
262
263 // Log entries with DELETED_ACTION must not show up unless the user has
264 // the necessary rights.
265 if ( !$user->isAllowed( 'deletedhistory' ) ) {
266 $bitmask = LogPage::DELETED_ACTION;
267 } elseif ( !$user->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
268 $bitmask = LogPage::DELETED_ACTION | LogPage::DELETED_RESTRICTED;
269 } else {
270 $bitmask = 0;
271 }
272 if ( $bitmask ) {
273 $conds[] = $dbr->makeList( [
274 'rc_type != ' . RC_LOG,
275 $dbr->bitAnd( 'rc_deleted', $bitmask ) . " != $bitmask",
276 ], LIST_OR );
277 }
278
279 ChangeTags::modifyDisplayQuery(
280 $tables,
281 $fields,
282 $conds,
283 $join_conds,
284 $query_options,
285 ''
286 );
287
288 $this->runMainQueryHook( $tables, $fields, $conds, $query_options, $join_conds, $opts );
289
290 return $dbr->select(
291 $tables,
292 $fields,
293 $conds,
294 __METHOD__,
295 $query_options,
296 $join_conds
297 );
298 }
299
300 protected function runMainQueryHook( &$tables, &$fields, &$conds, &$query_options,
301 &$join_conds, $opts
302 ) {
303 return parent::runMainQueryHook( $tables, $fields, $conds, $query_options, $join_conds, $opts )
304 && Hooks::run(
305 'SpecialWatchlistQuery',
306 [ &$conds, &$tables, &$join_conds, &$fields, $opts ],
307 '1.23'
308 );
309 }
310
311 /**
312 * Return a IDatabase object for reading
313 *
314 * @return IDatabase
315 */
316 protected function getDB() {
317 return wfGetDB( DB_REPLICA, 'watchlist' );
318 }
319
320 /**
321 * Output feed links.
322 */
323 public function outputFeedLinks() {
324 $user = $this->getUser();
325 $wlToken = $user->getTokenFromOption( 'watchlisttoken' );
326 if ( $wlToken ) {
327 $this->addFeedLinks( [
328 'action' => 'feedwatchlist',
329 'allrev' => 1,
330 'wlowner' => $user->getName(),
331 'wltoken' => $wlToken,
332 ] );
333 }
334 }
335
336 /**
337 * Build and output the actual changes list.
338 *
339 * @param ResultWrapper $rows Database rows
340 * @param FormOptions $opts
341 */
342 public function outputChangesList( $rows, $opts ) {
343 $dbr = $this->getDB();
344 $user = $this->getUser();
345 $output = $this->getOutput();
346
347 # Show a message about replica DB lag, if applicable
348 $lag = wfGetLB()->safeGetLag( $dbr );
349 if ( $lag > 0 ) {
350 $output->showLagWarning( $lag );
351 }
352
353 # If no rows to display, show message before try to render the list
354 if ( $rows->numRows() == 0 ) {
355 $output->wrapWikiMsg(
356 "<div class='mw-changeslist-empty'>\n$1\n</div>", 'recentchanges-noresult'
357 );
358 return;
359 }
360
361 $dbr->dataSeek( $rows, 0 );
362
363 $list = ChangesList::newFromContext( $this->getContext() );
364 $list->setWatchlistDivs();
365 $list->initChangesListRows( $rows );
366 $dbr->dataSeek( $rows, 0 );
367
368 if ( $this->getConfig()->get( 'RCShowWatchingUsers' )
369 && $user->getOption( 'shownumberswatching' )
370 ) {
371 $watchedItemStore = MediaWikiServices::getInstance()->getWatchedItemStore();
372 }
373
374 $s = $list->beginRecentChangesList();
375 $userShowHiddenCats = $this->getUser()->getBoolOption( 'showhiddencats' );
376 $counter = 1;
377 foreach ( $rows as $obj ) {
378 # Make RC entry
379 $rc = RecentChange::newFromRow( $obj );
380
381 # Skip CatWatch entries for hidden cats based on user preference
382 if (
383 $rc->getAttribute( 'rc_type' ) == RC_CATEGORIZE &&
384 !$userShowHiddenCats &&
385 $rc->getParam( 'hidden-cat' )
386 ) {
387 continue;
388 }
389
390 $rc->counter = $counter++;
391
392 if ( $this->getConfig()->get( 'ShowUpdatedMarker' ) ) {
393 $updated = $obj->wl_notificationtimestamp;
394 } else {
395 $updated = false;
396 }
397
398 if ( isset( $watchedItemStore ) ) {
399 $rcTitleValue = new TitleValue( (int)$obj->rc_namespace, $obj->rc_title );
400 $rc->numberofWatchingusers = $watchedItemStore->countWatchers( $rcTitleValue );
401 } else {
402 $rc->numberofWatchingusers = 0;
403 }
404
405 $changeLine = $list->recentChangesLine( $rc, $updated, $counter );
406 if ( $changeLine !== false ) {
407 $s .= $changeLine;
408 }
409 }
410 $s .= $list->endRecentChangesList();
411
412 $output->addHTML( $s );
413 }
414
415 /**
416 * Set the text to be displayed above the changes
417 *
418 * @param FormOptions $opts
419 * @param int $numRows Number of rows in the result to show after this header
420 */
421 public function doHeader( $opts, $numRows ) {
422 $user = $this->getUser();
423 $out = $this->getOutput();
424
425 $out->addSubtitle(
426 $this->msg( 'watchlistfor2', $user->getName() )
427 ->rawParams( SpecialEditWatchlist::buildTools(
428 $this->getLanguage(),
429 $this->getLinkRenderer()
430 ) )
431 );
432
433 $this->setTopText( $opts );
434
435 $lang = $this->getLanguage();
436 if ( $opts['days'] > 0 ) {
437 $days = $opts['days'];
438 } else {
439 $days = $this->getConfig()->get( 'RCMaxAge' ) / ( 3600 * 24 );
440 }
441 $timestamp = wfTimestampNow();
442 $wlInfo = $this->msg( 'wlnote' )->numParams( $numRows, round( $days * 24 ) )->params(
443 $lang->userDate( $timestamp, $user ), $lang->userTime( $timestamp, $user )
444 )->parse() . "<br />\n";
445
446 $nondefaults = $opts->getChangedValues();
447 $cutofflinks = $this->msg( 'wlshowtime' ) . ' ' . $this->cutoffselector( $opts );
448
449 # Spit out some control panel links
450 $filters = [
451 'hideminor' => 'wlshowhideminor',
452 'hidebots' => 'wlshowhidebots',
453 'hideanons' => 'wlshowhideanons',
454 'hideliu' => 'wlshowhideliu',
455 'hidemyself' => 'wlshowhidemine',
456 'hidepatrolled' => 'wlshowhidepatr'
457 ];
458
459 if ( $this->getConfig()->get( 'RCWatchCategoryMembership' ) ) {
460 $filters['hidecategorization'] = 'wlshowhidecategorization';
461 }
462
463 foreach ( $this->getRenderableCustomFilters( $this->getCustomFilters() ) as $key => $params ) {
464 $filters[$key] = $params['msg'];
465 }
466
467 // Disable some if needed
468 if ( !$user->useRCPatrol() ) {
469 unset( $filters['hidepatrolled'] );
470 }
471
472 $links = [];
473 foreach ( $filters as $name => $msg ) {
474 $links[] = $this->showHideCheck( $nondefaults, $msg, $name, $opts[$name] );
475 }
476
477 $hiddenFields = $nondefaults;
478 $hiddenFields['action'] = 'submit';
479 unset( $hiddenFields['namespace'] );
480 unset( $hiddenFields['invert'] );
481 unset( $hiddenFields['associated'] );
482 unset( $hiddenFields['days'] );
483 foreach ( $filters as $key => $value ) {
484 unset( $hiddenFields[$key] );
485 }
486
487 # Create output
488 $form = '';
489
490 # Namespace filter and put the whole form together.
491 $form .= $wlInfo;
492 $form .= $cutofflinks;
493 $form .= $this->msg( 'watchlist-hide' ) .
494 $this->msg( 'colon-separator' )->escaped() .
495 implode( ' ', $links );
496 $form .= "\n<br />\n";
497 $form .= Html::namespaceSelector(
498 [
499 'selected' => $opts['namespace'],
500 'all' => '',
501 'label' => $this->msg( 'namespace' )->text()
502 ], [
503 'name' => 'namespace',
504 'id' => 'namespace',
505 'class' => 'namespaceselector',
506 ]
507 ) . "\n";
508 $form .= '<span class="mw-input-with-label">' . Xml::checkLabel(
509 $this->msg( 'invert' )->text(),
510 'invert',
511 'nsinvert',
512 $opts['invert'],
513 [ 'title' => $this->msg( 'tooltip-invert' )->text() ]
514 ) . "</span>\n";
515 $form .= '<span class="mw-input-with-label">' . Xml::checkLabel(
516 $this->msg( 'namespace_association' )->text(),
517 'associated',
518 'nsassociated',
519 $opts['associated'],
520 [ 'title' => $this->msg( 'tooltip-namespace_association' )->text() ]
521 ) . "</span>\n";
522 $form .= Xml::submitButton( $this->msg( 'watchlist-submit' )->text() ) . "\n";
523 foreach ( $hiddenFields as $key => $value ) {
524 $form .= Html::hidden( $key, $value ) . "\n";
525 }
526 $form .= Xml::closeElement( 'fieldset' ) . "\n";
527 $form .= Xml::closeElement( 'form' ) . "\n";
528 $this->getOutput()->addHTML( $form );
529
530 $this->setBottomText( $opts );
531 }
532
533 function cutoffselector( $options ) {
534 // Cast everything to strings immediately, so that we know all of the values have the same
535 // precision, and can be compared with '==='. 2/24 has a few more decimal places than its
536 // default string representation, for example, and would confuse comparisons.
537
538 // Misleadingly, the 'days' option supports hours too.
539 $days = array_map( 'strval', [ 1/24, 2/24, 6/24, 12/24, 1, 3, 7 ] );
540
541 $userWatchlistOption = (string)$this->getUser()->getOption( 'watchlistdays' );
542 // add the user preference, if it isn't available already
543 if ( !in_array( $userWatchlistOption, $days ) && $userWatchlistOption !== '0' ) {
544 $days[] = $userWatchlistOption;
545 }
546
547 $maxDays = (string)( $this->getConfig()->get( 'RCMaxAge' ) / ( 3600 * 24 ) );
548 // add the maximum possible value, if it isn't available already
549 if ( !in_array( $maxDays, $days ) ) {
550 $days[] = $maxDays;
551 }
552
553 $selected = (string)$options['days'];
554 if ( $selected <= 0 ) {
555 $selected = $maxDays;
556 }
557
558 // add the currently selected value, if it isn't available already
559 if ( !in_array( $selected, $days ) ) {
560 $days[] = $selected;
561 }
562
563 $select = new XmlSelect( 'days', 'days', $selected );
564
565 asort( $days );
566 foreach ( $days as $value ) {
567 if ( $value < 1 ) {
568 $name = $this->msg( 'hours' )->numParams( $value * 24 )->text();
569 } else {
570 $name = $this->msg( 'days' )->numParams( $value )->text();
571 }
572 $select->addOption( $name, $value );
573 }
574
575 return $select->getHTML() . "\n<br />\n";
576 }
577
578 function setTopText( FormOptions $opts ) {
579 $nondefaults = $opts->getChangedValues();
580 $form = "";
581 $user = $this->getUser();
582
583 $numItems = $this->countItems();
584 $showUpdatedMarker = $this->getConfig()->get( 'ShowUpdatedMarker' );
585
586 // Show watchlist header
587 $form .= "<p>";
588 if ( $numItems == 0 ) {
589 $form .= $this->msg( 'nowatchlist' )->parse() . "\n";
590 } else {
591 $form .= $this->msg( 'watchlist-details' )->numParams( $numItems )->parse() . "\n";
592 if ( $this->getConfig()->get( 'EnotifWatchlist' )
593 && $user->getOption( 'enotifwatchlistpages' )
594 ) {
595 $form .= $this->msg( 'wlheader-enotif' )->parse() . "\n";
596 }
597 if ( $showUpdatedMarker ) {
598 $form .= $this->msg( 'wlheader-showupdated' )->parse() . "\n";
599 }
600 }
601 $form .= "</p>";
602
603 if ( $numItems > 0 && $showUpdatedMarker ) {
604 $form .= Xml::openElement( 'form', [ 'method' => 'post',
605 'action' => $this->getPageTitle()->getLocalURL(),
606 'id' => 'mw-watchlist-resetbutton' ] ) . "\n" .
607 Xml::submitButton( $this->msg( 'enotif_reset' )->text(),
608 [ 'name' => 'mw-watchlist-reset-submit' ] ) . "\n" .
609 Html::hidden( 'reset', 'all' ) . "\n";
610 foreach ( $nondefaults as $key => $value ) {
611 $form .= Html::hidden( $key, $value ) . "\n";
612 }
613 $form .= Xml::closeElement( 'form' ) . "\n";
614 }
615
616 $form .= Xml::openElement( 'form', [
617 'method' => 'get',
618 'action' => wfScript(),
619 'id' => 'mw-watchlist-form'
620 ] );
621 $form .= Html::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
622 $form .= Xml::fieldset(
623 $this->msg( 'watchlist-options' )->text(),
624 false,
625 [ 'id' => 'mw-watchlist-options' ]
626 );
627
628 $form .= $this->makeLegend();
629
630 $this->getOutput()->addHTML( $form );
631 }
632
633 protected function showHideCheck( $options, $message, $name, $value ) {
634 $options[$name] = 1 - (int)$value;
635
636 return '<span class="mw-input-with-label">' . Xml::checkLabel(
637 $this->msg( $message, '' )->text(),
638 $name,
639 $name,
640 (int)$value
641 ) . '</span>';
642 }
643
644 /**
645 * Count the number of paired items on a user's watchlist.
646 * The assumption made here is that when a subject page is watched a talk page is also watched.
647 * Hence the number of individual items is halved.
648 *
649 * @return int
650 */
651 protected function countItems() {
652 $store = MediaWikiServices::getInstance()->getWatchedItemStore();
653 $count = $store->countWatchedItems( $this->getUser() );
654 return floor( $count / 2 );
655 }
656 }