Merge "Remove duplicate array keys from tests"
[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 $output->addModules( array(
48 'mediawiki.special.changeslist.visitedstatus',
49 ) );
50
51 $mode = SpecialEditWatchlist::getMode( $request, $subpage );
52 if ( $mode !== false ) {
53 if ( $mode === SpecialEditWatchlist::EDIT_RAW ) {
54 $title = SpecialPage::getTitleFor( 'EditWatchlist', 'raw' );
55 } elseif ( $mode === SpecialEditWatchlist::EDIT_CLEAR ) {
56 $title = SpecialPage::getTitleFor( 'EditWatchlist', 'clear' );
57 } else {
58 $title = SpecialPage::getTitleFor( 'EditWatchlist' );
59 }
60
61 $output->redirect( $title->getLocalURL() );
62
63 return;
64 }
65
66 $this->checkPermissions();
67
68 $user = $this->getUser();
69 $opts = $this->getOptions();
70
71 $config = $this->getConfig();
72 if ( ( $config->get( 'EnotifWatchlist' ) || $config->get( 'ShowUpdatedMarker' ) )
73 && $request->getVal( 'reset' )
74 && $request->wasPosted()
75 ) {
76 $user->clearAllNotifications();
77 $output->redirect( $this->getPageTitle()->getFullURL( $opts->getChangedValues() ) );
78
79 return;
80 }
81
82 parent::execute( $subpage );
83 }
84
85 /**
86 * Return an array of subpages that this special page will accept.
87 *
88 * @see also SpecialEditWatchlist::getSubpagesForPrefixSearch
89 * @return string[] subpages
90 */
91 public function getSubpagesForPrefixSearch() {
92 return array(
93 'clear',
94 'edit',
95 'raw',
96 );
97 }
98
99 /**
100 * Get a FormOptions object containing the default options
101 *
102 * @return FormOptions
103 */
104 public function getDefaultOptions() {
105 $opts = parent::getDefaultOptions();
106 $user = $this->getUser();
107
108 $opts->add( 'days', $user->getOption( 'watchlistdays' ), FormOptions::FLOAT );
109 $opts->add( 'extended', $user->getBoolOption( 'extendwatchlist' ) );
110 if ( $this->getRequest()->getVal( 'action' ) == 'submit' ) {
111 // The user has submitted the form, so we dont need the default values
112 return $opts;
113 }
114
115 $opts->add( 'hideminor', $user->getBoolOption( 'watchlisthideminor' ) );
116 $opts->add( 'hidebots', $user->getBoolOption( 'watchlisthidebots' ) );
117 $opts->add( 'hideanons', $user->getBoolOption( 'watchlisthideanons' ) );
118 $opts->add( 'hideliu', $user->getBoolOption( 'watchlisthideliu' ) );
119 $opts->add( 'hidepatrolled', $user->getBoolOption( 'watchlisthidepatrolled' ) );
120 $opts->add( 'hidemyself', $user->getBoolOption( 'watchlisthideown' ) );
121 $opts->add( 'hidecategorization', $user->getBoolOption( 'watchlisthidecategorization' ) );
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 $out = $this->getOutput();
407
408 // if the user wishes, that the watchlist is reloaded, whenever a filter changes,
409 // add the module for that
410 if ( $user->getBoolOption( 'watchlistreloadautomatically' ) ) {
411 $out->addModules( array( 'mediawiki.special.watchlist' ) );
412 }
413
414 $out->addSubtitle(
415 $this->msg( 'watchlistfor2', $user->getName() )
416 ->rawParams( SpecialEditWatchlist::buildTools( null ) )
417 );
418
419 $this->setTopText( $opts );
420
421 $lang = $this->getLanguage();
422 if ( $opts['days'] > 0 ) {
423 $days = $opts['days'];
424 } else {
425 $days = $this->getConfig()->get( 'RCMaxAge' ) / ( 3600 * 24 );
426 }
427 $timestamp = wfTimestampNow();
428 $wlInfo = $this->msg( 'wlnote' )->numParams( $numRows, round( $days * 24 ) )->params(
429 $lang->userDate( $timestamp, $user ), $lang->userTime( $timestamp, $user )
430 )->parse() . "<br />\n";
431
432 $nondefaults = $opts->getChangedValues();
433 $cutofflinks = $this->msg( 'wlshowtime' ) . ' ' . $this->cutoffselector( $opts );
434
435 # Spit out some control panel links
436 $filters = array(
437 'hideminor' => 'wlshowhideminor',
438 'hidebots' => 'wlshowhidebots',
439 'hideanons' => 'wlshowhideanons',
440 'hideliu' => 'wlshowhideliu',
441 'hidemyself' => 'wlshowhidemine',
442 'hidepatrolled' => 'wlshowhidepatr'
443 );
444
445 if ( $this->getConfig()->get( 'RCWatchCategoryMembership' ) ) {
446 $filters['hidecategorization'] = 'wlshowhidecategorization';
447 }
448
449 foreach ( $this->getCustomFilters() as $key => $params ) {
450 $filters[$key] = $params['msg'];
451 }
452 // Disable some if needed
453 if ( !$user->useRCPatrol() ) {
454 unset( $filters['hidepatrolled'] );
455 }
456
457 $links = array();
458 foreach ( $filters as $name => $msg ) {
459 $links[] = $this->showHideCheck( $nondefaults, $msg, $name, $opts[$name] );
460 }
461
462 $hiddenFields = $nondefaults;
463 $hiddenFields['action'] = 'submit';
464 unset( $hiddenFields['namespace'] );
465 unset( $hiddenFields['invert'] );
466 unset( $hiddenFields['associated'] );
467 unset( $hiddenFields['days'] );
468 foreach ( $filters as $key => $value ) {
469 unset( $hiddenFields[$key] );
470 }
471
472 # Create output
473 $form = '';
474
475 # Namespace filter and put the whole form together.
476 $form .= $wlInfo;
477 $form .= $cutofflinks;
478 $form .= $this->msg( 'watchlist-hide' ) .
479 $this->msg( 'colon-separator' )->escaped() .
480 implode( ' ', $links );
481 $form .= "\n<br />\n";
482 $form .= Html::namespaceSelector(
483 array(
484 'selected' => $opts['namespace'],
485 'all' => '',
486 'label' => $this->msg( 'namespace' )->text()
487 ), array(
488 'name' => 'namespace',
489 'id' => 'namespace',
490 'class' => 'namespaceselector',
491 )
492 ) . "\n";
493 $form .= '<span class="mw-input-with-label">' . Xml::checkLabel(
494 $this->msg( 'invert' )->text(),
495 'invert',
496 'nsinvert',
497 $opts['invert'],
498 array( 'title' => $this->msg( 'tooltip-invert' )->text() )
499 ) . "</span>\n";
500 $form .= '<span class="mw-input-with-label">' . Xml::checkLabel(
501 $this->msg( 'namespace_association' )->text(),
502 'associated',
503 'nsassociated',
504 $opts['associated'],
505 array( 'title' => $this->msg( 'tooltip-namespace_association' )->text() )
506 ) . "</span>\n";
507 $form .= Xml::submitButton( $this->msg( 'watchlist-submit' )->text() ) . "\n";
508 foreach ( $hiddenFields as $key => $value ) {
509 $form .= Html::hidden( $key, $value ) . "\n";
510 }
511 $form .= Xml::closeElement( 'fieldset' ) . "\n";
512 $form .= Xml::closeElement( 'form' ) . "\n";
513 $this->getOutput()->addHTML( $form );
514
515 $this->setBottomText( $opts );
516 }
517
518 function cutoffselector( $options ) {
519 // Cast everything to strings immediately, so that we know all of the values have the same
520 // precision, and can be compared with '==='. 2/24 has a few more decimal places than its
521 // default string representation, for example, and would confuse comparisons.
522
523 // Misleadingly, the 'days' option supports hours too.
524 $days = array_map( 'strval', array( 1/24, 2/24, 6/24, 12/24, 1, 3, 7 ) );
525
526 $userWatchlistOption = (string)$this->getUser()->getOption( 'watchlistdays' );
527 // add the user preference, if it isn't available already
528 if ( !in_array( $userWatchlistOption, $days ) && $userWatchlistOption !== '0' ) {
529 $days[] = $userWatchlistOption;
530 }
531
532 $maxDays = (string)( $this->getConfig()->get( 'RCMaxAge' ) / ( 3600 * 24 ) );
533 // add the maximum possible value, if it isn't available already
534 if ( !in_array( $maxDays, $days ) ) {
535 $days[] = $maxDays;
536 }
537
538 $selected = (string)$options['days'];
539 if ( $selected <= 0 ) {
540 $selected = $maxDays;
541 }
542
543 // add the currently selected value, if it isn't available already
544 if ( !in_array( $selected, $days ) ) {
545 $days[] = $selected;
546 }
547
548 $select = new XmlSelect( 'days', 'days', $selected );
549
550 asort( $days );
551 foreach ( $days as $value ) {
552 if ( $value < 1 ) {
553 $name = $this->msg( 'hours' )->numParams( $value * 24 )->text();
554 } else {
555 $name = $this->msg( 'days' )->numParams( $value )->text();
556 }
557 $select->addOption( $name, $value );
558 }
559
560 return $select->getHTML() . "\n<br />\n";
561 }
562
563 function setTopText( FormOptions $opts ) {
564 $nondefaults = $opts->getChangedValues();
565 $form = "";
566 $user = $this->getUser();
567
568 $dbr = $this->getDB();
569 $numItems = $this->countItems( $dbr );
570 $showUpdatedMarker = $this->getConfig()->get( 'ShowUpdatedMarker' );
571
572 // Show watchlist header
573 $form .= "<p>";
574 if ( $numItems == 0 ) {
575 $form .= $this->msg( 'nowatchlist' )->parse() . "\n";
576 } else {
577 $form .= $this->msg( 'watchlist-details' )->numParams( $numItems )->parse() . "\n";
578 if ( $this->getConfig()->get( 'EnotifWatchlist' )
579 && $user->getOption( 'enotifwatchlistpages' )
580 ) {
581 $form .= $this->msg( 'wlheader-enotif' )->parse() . "\n";
582 }
583 if ( $showUpdatedMarker ) {
584 $form .= $this->msg( 'wlheader-showupdated' )->parse() . "\n";
585 }
586 }
587 $form .= "</p>";
588
589 if ( $numItems > 0 && $showUpdatedMarker ) {
590 $form .= Xml::openElement( 'form', array( 'method' => 'post',
591 'action' => $this->getPageTitle()->getLocalURL(),
592 'id' => 'mw-watchlist-resetbutton' ) ) . "\n" .
593 Xml::submitButton( $this->msg( 'enotif_reset' )->text(), array( 'name' => 'dummy' ) ) . "\n" .
594 Html::hidden( 'reset', 'all' ) . "\n";
595 foreach ( $nondefaults as $key => $value ) {
596 $form .= Html::hidden( $key, $value ) . "\n";
597 }
598 $form .= Xml::closeElement( 'form' ) . "\n";
599 }
600
601 $form .= Xml::openElement( 'form', array(
602 'method' => 'get',
603 'action' => $this->getPageTitle()->getLocalURL(),
604 'id' => 'mw-watchlist-form'
605 ) );
606 $form .= Xml::fieldset(
607 $this->msg( 'watchlist-options' )->text(),
608 false,
609 array( 'id' => 'mw-watchlist-options' )
610 );
611
612 $form .= $this->makeLegend();
613
614 $this->getOutput()->addHTML( $form );
615 }
616
617 protected function showHideCheck( $options, $message, $name, $value ) {
618 $options[$name] = 1 - (int)$value;
619
620 return '<span class="mw-input-with-label">' . Xml::checkLabel(
621 $this->msg( $message, '' )->text(),
622 $name,
623 $name,
624 (int)$value
625 ) . '</span>';
626 }
627
628 /**
629 * Count the number of items on a user's watchlist
630 *
631 * @param IDatabase $dbr A database connection
632 * @return int
633 */
634 protected function countItems( $dbr ) {
635 # Fetch the raw count
636 $rows = $dbr->select( 'watchlist', array( 'count' => 'COUNT(*)' ),
637 array( 'wl_user' => $this->getUser()->getId() ), __METHOD__ );
638 $row = $dbr->fetchObject( $rows );
639 $count = $row->count;
640
641 return floor( $count / 2 );
642 }
643 }