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