Merge "DatabaseMssql: Don't duplicate body of makeList()"
[mediawiki.git] / includes / specials / SpecialWatchlist.php
blobdf9d363989ba0ec55eb0d40fb4c3ae60bf1e0185
1 <?php
2 /**
3 * Implements Special:Watchlist
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.
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.
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
20 * @file
21 * @ingroup SpecialPage
24 /**
25 * A special page that lists last changes made to the wiki,
26 * limited to user-defined list of titles.
28 * @ingroup SpecialPage
30 class SpecialWatchlist extends ChangesListSpecialPage {
31 public function __construct( $page = 'Watchlist', $restriction = 'viewmywatchlist' ) {
32 parent::__construct( $page, $restriction );
35 /**
36 * Main execution point
38 * @param string $subpage
40 function execute( $subpage ) {
41 // Anons don't get a watchlist
42 $this->requireLogin( 'watchlistanontext' );
44 $output = $this->getOutput();
45 $request = $this->getRequest();
47 $mode = SpecialEditWatchlist::getMode( $request, $subpage );
48 if ( $mode !== false ) {
49 if ( $mode === SpecialEditWatchlist::EDIT_RAW ) {
50 $title = SpecialPage::getTitleFor( 'EditWatchlist', 'raw' );
51 } elseif ( $mode === SpecialEditWatchlist::EDIT_CLEAR ) {
52 $title = SpecialPage::getTitleFor( 'EditWatchlist', 'clear' );
53 } else {
54 $title = SpecialPage::getTitleFor( 'EditWatchlist' );
57 $output->redirect( $title->getLocalURL() );
59 return;
62 $this->checkPermissions();
64 $user = $this->getUser();
65 $opts = $this->getOptions();
67 $config = $this->getConfig();
68 if ( ( $config->get( 'EnotifWatchlist' ) || $config->get( 'ShowUpdatedMarker' ) )
69 && $request->getVal( 'reset' )
70 && $request->wasPosted()
71 ) {
72 $user->clearAllNotifications();
73 $output->redirect( $this->getPageTitle()->getFullURL( $opts->getChangedValues() ) );
75 return;
78 parent::execute( $subpage );
81 /**
82 * Return an array of subpages that this special page will accept.
84 * @see also SpecialEditWatchlist::getSubpagesForPrefixSearch
85 * @return string[] subpages
87 public function getSubpagesForPrefixSearch() {
88 return array(
89 'clear',
90 'edit',
91 'raw',
95 /**
96 * Get a FormOptions object containing the default options
98 * @return FormOptions
100 public function getDefaultOptions() {
101 $opts = parent::getDefaultOptions();
102 $user = $this->getUser();
104 $opts->add( 'days', $user->getOption( 'watchlistdays' ), FormOptions::FLOAT );
106 $opts->add( 'hideminor', $user->getBoolOption( 'watchlisthideminor' ) );
107 $opts->add( 'hidebots', $user->getBoolOption( 'watchlisthidebots' ) );
108 $opts->add( 'hideanons', $user->getBoolOption( 'watchlisthideanons' ) );
109 $opts->add( 'hideliu', $user->getBoolOption( 'watchlisthideliu' ) );
110 $opts->add( 'hidepatrolled', $user->getBoolOption( 'watchlisthidepatrolled' ) );
111 $opts->add( 'hidemyself', $user->getBoolOption( 'watchlisthideown' ) );
113 $opts->add( 'extended', $user->getBoolOption( 'extendwatchlist' ) );
115 return $opts;
119 * Get custom show/hide filters
121 * @return array Map of filter URL param names to properties (msg/default)
123 protected function getCustomFilters() {
124 if ( $this->customFilters === null ) {
125 $this->customFilters = parent::getCustomFilters();
126 Hooks::run( 'SpecialWatchlistFilters', array( $this, &$this->customFilters ), '1.23' );
129 return $this->customFilters;
133 * Fetch values for a FormOptions object from the WebRequest associated with this instance.
135 * Maps old pre-1.23 request parameters Watchlist used to use (different from Recentchanges' ones)
136 * to the current ones.
138 * @param FormOptions $opts
139 * @return FormOptions
141 protected function fetchOptionsFromRequest( $opts ) {
142 static $compatibilityMap = array(
143 'hideMinor' => 'hideminor',
144 'hideBots' => 'hidebots',
145 'hideAnons' => 'hideanons',
146 'hideLiu' => 'hideliu',
147 'hidePatrolled' => 'hidepatrolled',
148 'hideOwn' => 'hidemyself',
151 $params = $this->getRequest()->getValues();
152 foreach ( $compatibilityMap as $from => $to ) {
153 if ( isset( $params[$from] ) ) {
154 $params[$to] = $params[$from];
155 unset( $params[$from] );
159 // Not the prettiest way to achieve this… FormOptions internally depends on data sanitization
160 // methods defined on WebRequest and removing this dependency would cause some code duplication.
161 $request = new DerivativeRequest( $this->getRequest(), $params );
162 $opts->fetchValuesFromRequest( $request );
164 return $opts;
168 * Return an array of conditions depending of options set in $opts
170 * @param FormOptions $opts
171 * @return array
173 public function buildMainQueryConds( FormOptions $opts ) {
174 $dbr = $this->getDB();
175 $conds = parent::buildMainQueryConds( $opts );
177 // Calculate cutoff
178 if ( $opts['days'] > 0 ) {
179 $conds[] = 'rc_timestamp > ' .
180 $dbr->addQuotes( $dbr->timestamp( time() - intval( $opts['days'] * 86400 ) ) );
183 return $conds;
187 * Process the query
189 * @param array $conds
190 * @param FormOptions $opts
191 * @return bool|ResultWrapper Result or false (for Recentchangeslinked only)
193 public function doMainQuery( $conds, $opts ) {
194 $dbr = $this->getDB();
195 $user = $this->getUser();
197 # Toggle watchlist content (all recent edits or just the latest)
198 if ( $opts['extended'] ) {
199 $limitWatchlist = $user->getIntOption( 'wllimit' );
200 $usePage = false;
201 } else {
202 # Top log Ids for a page are not stored
203 $nonRevisionTypes = array( RC_LOG );
204 Hooks::run( 'SpecialWatchlistGetNonRevisionTypes', array( &$nonRevisionTypes ) );
205 if ( $nonRevisionTypes ) {
206 $conds[] = $dbr->makeList(
207 array(
208 'rc_this_oldid=page_latest',
209 'rc_type' => $nonRevisionTypes,
211 LIST_OR
214 $limitWatchlist = 0;
215 $usePage = true;
218 $tables = array( 'recentchanges', 'watchlist' );
219 $fields = RecentChange::selectFields();
220 $query_options = array( 'ORDER BY' => 'rc_timestamp DESC' );
221 $join_conds = array(
222 'watchlist' => array(
223 'INNER JOIN',
224 array(
225 'wl_user' => $user->getId(),
226 'wl_namespace=rc_namespace',
227 'wl_title=rc_title'
232 if ( $this->getConfig()->get( 'ShowUpdatedMarker' ) ) {
233 $fields[] = 'wl_notificationtimestamp';
235 if ( $limitWatchlist ) {
236 $query_options['LIMIT'] = $limitWatchlist;
239 $rollbacker = $user->isAllowed( 'rollback' );
240 if ( $usePage || $rollbacker ) {
241 $tables[] = 'page';
242 $join_conds['page'] = array( 'LEFT JOIN', 'rc_cur_id=page_id' );
243 if ( $rollbacker ) {
244 $fields[] = 'page_latest';
248 // Log entries with DELETED_ACTION must not show up unless the user has
249 // the necessary rights.
250 if ( !$user->isAllowed( 'deletedhistory' ) ) {
251 $bitmask = LogPage::DELETED_ACTION;
252 } elseif ( !$user->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
253 $bitmask = LogPage::DELETED_ACTION | LogPage::DELETED_RESTRICTED;
254 } else {
255 $bitmask = 0;
257 if ( $bitmask ) {
258 $conds[] = $dbr->makeList( array(
259 'rc_type != ' . RC_LOG,
260 $dbr->bitAnd( 'rc_deleted', $bitmask ) . " != $bitmask",
261 ), LIST_OR );
264 ChangeTags::modifyDisplayQuery(
265 $tables,
266 $fields,
267 $conds,
268 $join_conds,
269 $query_options,
273 $this->runMainQueryHook( $tables, $fields, $conds, $query_options, $join_conds, $opts );
275 return $dbr->select(
276 $tables,
277 $fields,
278 $conds,
279 __METHOD__,
280 $query_options,
281 $join_conds
285 protected function runMainQueryHook( &$tables, &$fields, &$conds, &$query_options,
286 &$join_conds, $opts
288 return parent::runMainQueryHook( $tables, $fields, $conds, $query_options, $join_conds, $opts )
289 && Hooks::run(
290 'SpecialWatchlistQuery',
291 array( &$conds, &$tables, &$join_conds, &$fields, $opts ),
292 '1.23'
297 * Return a IDatabase object for reading
299 * @return IDatabase
301 protected function getDB() {
302 return wfGetDB( DB_SLAVE, 'watchlist' );
306 * Output feed links.
308 public function outputFeedLinks() {
309 $user = $this->getUser();
310 $wlToken = $user->getTokenFromOption( 'watchlisttoken' );
311 if ( $wlToken ) {
312 $this->addFeedLinks( array(
313 'action' => 'feedwatchlist',
314 'allrev' => 1,
315 'wlowner' => $user->getName(),
316 'wltoken' => $wlToken,
317 ) );
322 * Build and output the actual changes list.
324 * @param ResultWrapper $rows Database rows
325 * @param FormOptions $opts
327 public function outputChangesList( $rows, $opts ) {
328 $dbr = $this->getDB();
329 $user = $this->getUser();
330 $output = $this->getOutput();
332 # Show a message about slave lag, if applicable
333 $lag = wfGetLB()->safeGetLag( $dbr );
334 if ( $lag > 0 ) {
335 $output->showLagWarning( $lag );
338 # If no rows to display, show message before try to render the list
339 if ( $rows->numRows() == 0 ) {
340 $output->wrapWikiMsg(
341 "<div class='mw-changeslist-empty'>\n$1\n</div>", 'recentchanges-noresult'
343 return;
346 $dbr->dataSeek( $rows, 0 );
348 $list = ChangesList::newFromContext( $this->getContext() );
349 $list->setWatchlistDivs();
350 $list->initChangesListRows( $rows );
351 $dbr->dataSeek( $rows, 0 );
353 $s = $list->beginRecentChangesList();
354 $counter = 1;
355 foreach ( $rows as $obj ) {
356 # Make RC entry
357 $rc = RecentChange::newFromRow( $obj );
358 $rc->counter = $counter++;
360 if ( $this->getConfig()->get( 'ShowUpdatedMarker' ) ) {
361 $updated = $obj->wl_notificationtimestamp;
362 } else {
363 $updated = false;
366 if ( $this->getConfig()->get( 'RCShowWatchingUsers' )
367 && $user->getOption( 'shownumberswatching' )
369 $rc->numberofWatchingusers = $dbr->selectField( 'watchlist',
370 'COUNT(*)',
371 array(
372 'wl_namespace' => $obj->rc_namespace,
373 'wl_title' => $obj->rc_title,
375 __METHOD__ );
376 } else {
377 $rc->numberofWatchingusers = 0;
380 $changeLine = $list->recentChangesLine( $rc, $updated, $counter );
381 if ( $changeLine !== false ) {
382 $s .= $changeLine;
385 $s .= $list->endRecentChangesList();
387 $output->addHTML( $s );
391 * Set the text to be displayed above the changes
393 * @param FormOptions $opts
394 * @param int $numRows Number of rows in the result to show after this header
396 public function doHeader( $opts, $numRows ) {
397 $user = $this->getUser();
399 $this->getOutput()->addSubtitle(
400 $this->msg( 'watchlistfor2', $user->getName() )
401 ->rawParams( SpecialEditWatchlist::buildTools( null ) )
404 $this->setTopText( $opts );
406 $lang = $this->getLanguage();
407 $wlInfo = '';
408 if ( $opts['days'] > 0 ) {
409 $timestamp = wfTimestampNow();
410 $wlInfo = $this->msg( 'wlnote' )->numParams( $numRows, round( $opts['days'] * 24 ) )->params(
411 $lang->userDate( $timestamp, $user ), $lang->userTime( $timestamp, $user )
412 )->parse() . "<br />\n";
415 $nondefaults = $opts->getChangedValues();
416 $cutofflinks = $this->cutoffLinks( $opts['days'], $nondefaults ) . "<br />\n";
418 # Spit out some control panel links
419 $filters = array(
420 'hideminor' => 'rcshowhideminor',
421 'hidebots' => 'rcshowhidebots',
422 'hideanons' => 'rcshowhideanons',
423 'hideliu' => 'rcshowhideliu',
424 'hidemyself' => 'rcshowhidemine',
425 'hidepatrolled' => 'rcshowhidepatr'
427 foreach ( $this->getCustomFilters() as $key => $params ) {
428 $filters[$key] = $params['msg'];
430 // Disable some if needed
431 if ( !$user->useRCPatrol() ) {
432 unset( $filters['hidepatrolled'] );
435 $links = array();
436 foreach ( $filters as $name => $msg ) {
437 $links[] = $this->showHideLink( $nondefaults, $msg, $name, $opts[$name] );
440 $hiddenFields = $nondefaults;
441 unset( $hiddenFields['namespace'] );
442 unset( $hiddenFields['invert'] );
443 unset( $hiddenFields['associated'] );
445 # Create output
446 $form = '';
448 # Namespace filter and put the whole form together.
449 $form .= $wlInfo;
450 $form .= $cutofflinks;
451 $form .= $lang->pipeList( $links ) . "\n";
452 $form .= "<hr />\n<p>";
453 $form .= Html::namespaceSelector(
454 array(
455 'selected' => $opts['namespace'],
456 'all' => '',
457 'label' => $this->msg( 'namespace' )->text()
458 ), array(
459 'name' => 'namespace',
460 'id' => 'namespace',
461 'class' => 'namespaceselector',
463 ) . '&#160;';
464 $form .= Xml::checkLabel(
465 $this->msg( 'invert' )->text(),
466 'invert',
467 'nsinvert',
468 $opts['invert'],
469 array( 'title' => $this->msg( 'tooltip-invert' )->text() )
470 ) . '&#160;';
471 $form .= Xml::checkLabel(
472 $this->msg( 'namespace_association' )->text(),
473 'associated',
474 'nsassociated',
475 $opts['associated'],
476 array( 'title' => $this->msg( 'tooltip-namespace_association' )->text() )
477 ) . '&#160;';
478 $form .= Xml::submitButton( $this->msg( 'allpagessubmit' )->text() ) . "</p>\n";
479 foreach ( $hiddenFields as $key => $value ) {
480 $form .= Html::hidden( $key, $value ) . "\n";
482 $form .= Xml::closeElement( 'fieldset' ) . "\n";
483 $form .= Xml::closeElement( 'form' ) . "\n";
484 $this->getOutput()->addHTML( $form );
486 $this->setBottomText( $opts );
489 function setTopText( FormOptions $opts ) {
490 $nondefaults = $opts->getChangedValues();
491 $form = "";
492 $user = $this->getUser();
494 $dbr = $this->getDB();
495 $numItems = $this->countItems( $dbr );
496 $showUpdatedMarker = $this->getConfig()->get( 'ShowUpdatedMarker' );
498 // Show watchlist header
499 $form .= "<p>";
500 if ( $numItems == 0 ) {
501 $form .= $this->msg( 'nowatchlist' )->parse() . "\n";
502 } else {
503 $form .= $this->msg( 'watchlist-details' )->numParams( $numItems )->parse() . "\n";
504 if ( $this->getConfig()->get( 'EnotifWatchlist' )
505 && $user->getOption( 'enotifwatchlistpages' )
507 $form .= $this->msg( 'wlheader-enotif' )->parse() . "\n";
509 if ( $showUpdatedMarker ) {
510 $form .= $this->msg( 'wlheader-showupdated' )->parse() . "\n";
513 $form .= "</p>";
515 if ( $numItems > 0 && $showUpdatedMarker ) {
516 $form .= Xml::openElement( 'form', array( 'method' => 'post',
517 'action' => $this->getPageTitle()->getLocalURL(),
518 'id' => 'mw-watchlist-resetbutton' ) ) . "\n" .
519 Xml::submitButton( $this->msg( 'enotif_reset' )->text(), array( 'name' => 'dummy' ) ) . "\n" .
520 Html::hidden( 'reset', 'all' ) . "\n";
521 foreach ( $nondefaults as $key => $value ) {
522 $form .= Html::hidden( $key, $value ) . "\n";
524 $form .= Xml::closeElement( 'form' ) . "\n";
527 $form .= Xml::openElement( 'form', array(
528 'method' => 'post',
529 'action' => $this->getPageTitle()->getLocalURL(),
530 'id' => 'mw-watchlist-form'
531 ) );
532 $form .= Xml::fieldset(
533 $this->msg( 'watchlist-options' )->text(),
534 false,
535 array( 'id' => 'mw-watchlist-options' )
538 $form .= SpecialRecentChanges::makeLegend( $this->getContext() );
540 $this->getOutput()->addHTML( $form );
543 protected function showHideLink( $options, $message, $name, $value ) {
544 $label = $this->msg( $value ? 'show' : 'hide' )->escaped();
545 $options[$name] = 1 - (int)$value;
547 return $this->msg( $message )
548 ->rawParams( Linker::linkKnown( $this->getPageTitle(), $label, array(), $options ) )
549 ->escaped();
552 protected function hoursLink( $h, $options = array() ) {
553 $options['days'] = ( $h / 24.0 );
555 return Linker::linkKnown(
556 $this->getPageTitle(),
557 $this->getLanguage()->formatNum( $h ),
558 array(),
559 $options
563 protected function daysLink( $d, $options = array() ) {
564 $options['days'] = $d;
566 return Linker::linkKnown(
567 $this->getPageTitle(),
568 $this->getLanguage()->formatNum( $d ),
569 array(),
570 $options
575 * Returns html
577 * @param int $days This gets overwritten, so is not used
578 * @param array $options Query parameters for URL
579 * @return string
581 protected function cutoffLinks( $days, $options = array() ) {
582 global $wgRCMaxAge;
583 $watchlistMaxDays = ceil( $wgRCMaxAge / ( 3600 * 24 ) );
585 $hours = array( 1, 2, 6, 12 );
586 $days = array( 1, 3, 7, $watchlistMaxDays );
587 $i = 0;
588 foreach ( $hours as $h ) {
589 $hours[$i++] = $this->hoursLink( $h, $options );
591 $i = 0;
592 foreach ( $days as $d ) {
593 $days[$i++] = $this->daysLink( $d, $options );
596 return $this->msg( 'wlshowlast' )->rawParams(
597 $this->getLanguage()->pipeList( $hours ),
598 $this->getLanguage()->pipeList( $days ) )->parse();
602 * Count the number of items on a user's watchlist
604 * @param IDatabase $dbr A database connection
605 * @return int
607 protected function countItems( $dbr ) {
608 # Fetch the raw count
609 $rows = $dbr->select( 'watchlist', array( 'count' => 'COUNT(*)' ),
610 array( 'wl_user' => $this->getUser()->getId() ), __METHOD__ );
611 $row = $dbr->fetchObject( $rows );
612 $count = $row->count;
614 return floor( $count / 2 );