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