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