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