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