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