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