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