Minor refactoring
[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 SpecialPage {
24 protected $customFilters;
25
26 /**
27 * Constructor
28 */
29 public function __construct(){
30 parent::__construct( 'Watchlist' );
31 }
32
33 /**
34 * Execute
35 * @param $par Parameter passed to the page
36 */
37 function execute( $par ) {
38 global $wgUser, $wgOut, $wgLang, $wgRequest;
39 global $wgRCShowWatchingUsers, $wgEnotifWatchlist, $wgShowUpdatedMarker;
40
41 // Add feed links
42 $wlToken = $wgUser->getOption( 'watchlisttoken' );
43 if ( !$wlToken ) {
44 $wlToken = sha1( mt_rand() . microtime( true ) );
45 $wgUser->setOption( 'watchlisttoken', $wlToken );
46 $wgUser->saveSettings();
47 }
48
49 global $wgFeedClasses;
50 $apiParams = array( 'action' => 'feedwatchlist', 'allrev' => 'allrev',
51 'wlowner' => $wgUser->getName(), 'wltoken' => $wlToken );
52 $feedTemplate = wfScript( 'api' ) . '?';
53
54 foreach( $wgFeedClasses as $format => $class ) {
55 $theseParams = $apiParams + array( 'feedformat' => $format );
56 $url = $feedTemplate . wfArrayToCGI( $theseParams );
57 $wgOut->addFeedLink( $format, $url );
58 }
59
60 $skin = $this->getSkin();
61 $wgOut->setRobotPolicy( 'noindex,nofollow' );
62
63 # Anons don't get a watchlist
64 if( $wgUser->isAnon() ) {
65 $wgOut->setPageTitle( wfMsg( 'watchnologin' ) );
66 $llink = $skin->linkKnown(
67 SpecialPage::getTitleFor( 'Userlogin' ),
68 wfMsgHtml( 'loginreqlink' ),
69 array(),
70 array( 'returnto' => $this->getTitle()->getPrefixedText() )
71 );
72 $wgOut->addWikiMsgArray( 'watchlistanontext', array( $llink ), array( 'replaceafter' ) );
73 return;
74 }
75
76 $wgOut->setPageTitle( wfMsg( 'watchlist' ) );
77
78 $sub = wfMsgExt(
79 'watchlistfor2',
80 array( 'parseinline', 'replaceafter' ),
81 $wgUser->getName(),
82 SpecialEditWatchlist::buildTools( $skin )
83 );
84 $wgOut->setSubtitle( $sub );
85
86 $mode = SpecialEditWatchlist::getMode( $wgRequest, $par );
87 if( $mode !== false ) {
88 # TODO: localise?
89 switch( $mode ){
90 case SpecialEditWatchlist::EDIT_CLEAR:
91 $mode = 'clear';
92 break;
93 case SpecialEditWatchlist::EDIT_RAW:
94 $mode = 'raw';
95 break;
96 default:
97 $mode = null;
98 }
99 $title = SpecialPage::getTitleFor( 'EditWatchlist', $mode );
100 $wgOut->redirect( $title->getLocalUrl() );
101 return;
102 }
103
104 $uid = $wgUser->getId();
105 if( ( $wgEnotifWatchlist || $wgShowUpdatedMarker ) && $wgRequest->getVal( 'reset' ) &&
106 $wgRequest->wasPosted() )
107 {
108 $wgUser->clearAllNotifications( $uid );
109 $wgOut->redirect( $this->getTitle()->getFullUrl() );
110 return;
111 }
112
113 // @TODO: use FormOptions!
114 $defaults = array(
115 /* float */ 'days' => floatval( $wgUser->getOption( 'watchlistdays' ) ), /* 3.0 or 0.5, watch further below */
116 /* bool */ 'hideMinor' => (int)$wgUser->getBoolOption( 'watchlisthideminor' ),
117 /* bool */ 'hideBots' => (int)$wgUser->getBoolOption( 'watchlisthidebots' ),
118 /* bool */ 'hideAnons' => (int)$wgUser->getBoolOption( 'watchlisthideanons' ),
119 /* bool */ 'hideLiu' => (int)$wgUser->getBoolOption( 'watchlisthideliu' ),
120 /* bool */ 'hidePatrolled' => (int)$wgUser->getBoolOption( 'watchlisthidepatrolled' ),
121 /* bool */ 'hideOwn' => (int)$wgUser->getBoolOption( 'watchlisthideown' ),
122 /* ? */ 'namespace' => 'all',
123 /* ? */ 'invert' => false,
124 );
125 $this->customFilters = array();
126 wfRunHooks( 'SpecialWatchlistFilters', array( $this, &$this->customFilters ) );
127 foreach( $this->customFilters as $key => $params ) {
128 $defaults[$key] = $params['msg'];
129 }
130
131 # Extract variables from the request, falling back to user preferences or
132 # other default values if these don't exist
133 $prefs['days'] = floatval( $wgUser->getOption( 'watchlistdays' ) );
134 $prefs['hideminor'] = $wgUser->getBoolOption( 'watchlisthideminor' );
135 $prefs['hidebots'] = $wgUser->getBoolOption( 'watchlisthidebots' );
136 $prefs['hideanons'] = $wgUser->getBoolOption( 'watchlisthideanons' );
137 $prefs['hideliu'] = $wgUser->getBoolOption( 'watchlisthideliu' );
138 $prefs['hideown' ] = $wgUser->getBoolOption( 'watchlisthideown' );
139 $prefs['hidepatrolled' ] = $wgUser->getBoolOption( 'watchlisthidepatrolled' );
140
141 # Get query variables
142 $values = array();
143 $values['days'] = $wgRequest->getVal( 'days', $prefs['days'] );
144 $values['hideMinor'] = (int)$wgRequest->getBool( 'hideMinor', $prefs['hideminor'] );
145 $values['hideBots'] = (int)$wgRequest->getBool( 'hideBots' , $prefs['hidebots'] );
146 $values['hideAnons'] = (int)$wgRequest->getBool( 'hideAnons', $prefs['hideanons'] );
147 $values['hideLiu'] = (int)$wgRequest->getBool( 'hideLiu' , $prefs['hideliu'] );
148 $values['hideOwn'] = (int)$wgRequest->getBool( 'hideOwn' , $prefs['hideown'] );
149 $values['hidePatrolled'] = (int)$wgRequest->getBool( 'hidePatrolled', $prefs['hidepatrolled'] );
150 foreach( $this->customFilters as $key => $params ) {
151 $values[$key] = (int)$wgRequest->getBool( $key );
152 }
153
154 # Get namespace value, if supplied, and prepare a WHERE fragment
155 $nameSpace = $wgRequest->getIntOrNull( 'namespace' );
156 $invert = $wgRequest->getIntOrNull( 'invert' );
157 if ( !is_null( $nameSpace ) ) {
158 $nameSpace = intval( $nameSpace ); // paranioa
159 if ( $invert ) {
160 $nameSpaceClause = "rc_namespace != $nameSpace";
161 } else {
162 $nameSpaceClause = "rc_namespace = $nameSpace";
163 }
164 } else {
165 $nameSpace = '';
166 $nameSpaceClause = '';
167 }
168 $values['namespace'] = $nameSpace;
169 $values['invert'] = $invert;
170
171 $dbr = wfGetDB( DB_SLAVE, 'watchlist' );
172 $recentchanges = $dbr->tableName( 'recentchanges' );
173
174 $watchlistCount = $dbr->selectField( 'watchlist', 'COUNT(*)',
175 array( 'wl_user' => $uid ), __METHOD__ );
176 // Adjust for page X, talk:page X, which are both stored separately,
177 // but treated together
178 $nitems = floor( $watchlistCount / 2 );
179
180 if( is_null( $values['days'] ) || !is_numeric( $values['days'] ) ) {
181 $big = 1000; /* The magical big */
182 if( $nitems > $big ) {
183 # Set default cutoff shorter
184 $values['days'] = $defaults['days'] = (12.0 / 24.0); # 12 hours...
185 } else {
186 $values['days'] = $defaults['days']; # default cutoff for shortlisters
187 }
188 } else {
189 $values['days'] = floatval( $values['days'] );
190 }
191
192 // Dump everything here
193 $nondefaults = array();
194 foreach ( $defaults as $name => $defValue ) {
195 wfAppendToArrayIfNotDefault( $name, $values[$name], $defaults, $nondefaults );
196 }
197
198 if( $nitems == 0 ) {
199 $wgOut->addWikiMsg( 'nowatchlist' );
200 return;
201 }
202
203 # Possible where conditions
204 $conds = array();
205
206 if( $values['days'] > 0 ) {
207 $conds[] = "rc_timestamp > '".$dbr->timestamp( time() - intval( $values['days'] * 86400 ) )."'";
208 }
209
210 # If the watchlist is relatively short, it's simplest to zip
211 # down its entirety and then sort the results.
212
213 # If it's relatively long, it may be worth our while to zip
214 # through the time-sorted page list checking for watched items.
215
216 # Up estimate of watched items by 15% to compensate for talk pages...
217
218 # Toggles
219 if( $values['hideOwn'] ) {
220 $conds[] = "rc_user != $uid";
221 }
222 if( $values['hideBots'] ) {
223 $conds[] = 'rc_bot = 0';
224 }
225 if( $values['hideMinor'] ) {
226 $conds[] = 'rc_minor = 0';
227 }
228 if( $values['hideLiu'] ) {
229 $conds[] = 'rc_user = 0';
230 }
231 if( $values['hideAnons'] ) {
232 $conds[] = 'rc_user != 0';
233 }
234 if ( $wgUser->useRCPatrol() && $values['hidePatrolled'] ) {
235 $conds[] = 'rc_patrolled != 1';
236 }
237 if ( $nameSpaceClause ) {
238 $conds[] = $nameSpaceClause;
239 }
240
241 # Toggle watchlist content (all recent edits or just the latest)
242 if( $wgUser->getOption( 'extendwatchlist' ) ) {
243 $limitWatchlist = intval( $wgUser->getOption( 'wllimit' ) );
244 $usePage = false;
245 } else {
246 # Top log Ids for a page are not stored
247 $conds[] = 'rc_this_oldid=page_latest OR rc_type=' . RC_LOG;
248 $limitWatchlist = 0;
249 $usePage = true;
250 }
251
252 # Show a message about slave lag, if applicable
253 $lag = $dbr->getLag();
254 if( $lag > 0 ) {
255 $wgOut->showLagWarning( $lag );
256 }
257
258 # Create output form
259 $form = Xml::fieldset( wfMsg( 'watchlist-options' ), false, array( 'id' => 'mw-watchlist-options' ) );
260
261 # Show watchlist header
262 $form .= wfMsgExt( 'watchlist-details', array( 'parseinline' ), $wgLang->formatNum( $nitems ) );
263
264 if( $wgUser->getOption( 'enotifwatchlistpages' ) && $wgEnotifWatchlist) {
265 $form .= wfMsgExt( 'wlheader-enotif', 'parse' ) . "\n";
266 }
267 if( $wgShowUpdatedMarker ) {
268 $form .= Xml::openElement( 'form', array( 'method' => 'post',
269 'action' => $this->getTitle()->getLocalUrl(),
270 'id' => 'mw-watchlist-resetbutton' ) ) .
271 wfMsgExt( 'wlheader-showupdated', array( 'parseinline' ) ) . ' ' .
272 Xml::submitButton( wfMsg( 'enotif_reset' ), array( 'name' => 'dummy' ) ) .
273 Html::hidden( 'reset', 'all' ) .
274 Xml::closeElement( 'form' );
275 }
276 $form .= '<hr />';
277
278 $tables = array( 'recentchanges', 'watchlist' );
279 $fields = array( "{$recentchanges}.*" );
280 $join_conds = array(
281 'watchlist' => array('INNER JOIN',"wl_user='{$uid}' AND wl_namespace=rc_namespace AND wl_title=rc_title"),
282 );
283 $options = array( 'ORDER BY' => 'rc_timestamp DESC' );
284 if( $wgShowUpdatedMarker ) {
285 $fields[] = 'wl_notificationtimestamp';
286 }
287 if( $limitWatchlist ) {
288 $options['LIMIT'] = $limitWatchlist;
289 }
290
291 $rollbacker = $wgUser->isAllowed('rollback');
292 if ( $usePage || $rollbacker ) {
293 $tables[] = 'page';
294 $join_conds['page'] = array('LEFT JOIN','rc_cur_id=page_id');
295 if ( $rollbacker ) {
296 $fields[] = 'page_latest';
297 }
298 }
299
300 ChangeTags::modifyDisplayQuery( $tables, $fields, $conds, $join_conds, $options, '' );
301 wfRunHooks('SpecialWatchlistQuery', array(&$conds,&$tables,&$join_conds,&$fields) );
302
303 $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $options, $join_conds );
304 $numRows = $dbr->numRows( $res );
305
306 /* Start bottom header */
307
308 $wlInfo = '';
309 if( $values['days'] >= 1 ) {
310 $wlInfo = wfMsgExt( 'rcnote', 'parseinline',
311 $wgLang->formatNum( $numRows ),
312 $wgLang->formatNum( $values['days'] ),
313 $wgLang->timeAndDate( wfTimestampNow(), true ),
314 $wgLang->date( wfTimestampNow(), true ),
315 $wgLang->time( wfTimestampNow(), true )
316 ) . '<br />';
317 } elseif( $values['days'] > 0 ) {
318 $wlInfo = wfMsgExt( 'wlnote', 'parseinline',
319 $wgLang->formatNum( $numRows ),
320 $wgLang->formatNum( round( $values['days'] * 24 ) )
321 ) . '<br />';
322 }
323
324 $cutofflinks = "\n" . self::cutoffLinks( $values['days'], 'Watchlist', $nondefaults ) . "<br />\n";
325
326 $thisTitle = SpecialPage::getTitleFor( 'Watchlist' );
327
328 # Spit out some control panel links
329 $filters = array(
330 'hideMinor' => 'rcshowhideminor',
331 'hideBots' => 'rcshowhidebots',
332 'hideAnons' => 'rcshowhideanons',
333 'hideLiu' => 'rcshowhideliu',
334 'hideOwn' => 'rcshowhidemine',
335 'hidePatrolled' => 'rcshowhidepatr'
336 );
337 foreach ( $this->customFilters as $key => $params ) {
338 $filters[$key] = $params['msg'];
339 }
340 // Disable some if needed
341 if ( !$wgUser->useNPPatrol() ) {
342 unset( $filters['hidePatrolled'] );
343 }
344
345 $links = array();
346 foreach( $filters as $name => $msg ) {
347 $links[] = self::showHideLink( $nondefaults, $msg, $name, $values[$name] );
348 }
349
350 # Namespace filter and put the whole form together.
351 $form .= $wlInfo;
352 $form .= $cutofflinks;
353 $form .= $wgLang->pipeList( $links );
354 $form .= Xml::openElement( 'form', array( 'method' => 'post', 'action' => $thisTitle->getLocalUrl(), 'id' => 'mw-watchlist-form-namespaceselector' ) );
355 $form .= '<hr /><p>';
356 $form .= Xml::label( wfMsg( 'namespace' ), 'namespace' ) . '&#160;';
357 $form .= Xml::namespaceSelector( $nameSpace, '' ) . '&#160;';
358 $form .= Xml::checkLabel( wfMsg('invert'), 'invert', 'nsinvert', $invert ) . '&#160;';
359 $form .= Xml::submitButton( wfMsg( 'allpagessubmit' ) ) . '</p>';
360 $form .= Html::hidden( 'days', $values['days'] );
361 foreach ( $filters as $key => $msg ) {
362 if ( $values[$key] ) {
363 $form .= Html::hidden( $key, 1 );
364 }
365 }
366 $form .= Xml::closeElement( 'form' );
367 $form .= Xml::closeElement( 'fieldset' );
368 $wgOut->addHTML( $form );
369
370 # If there's nothing to show, stop here
371 if( $numRows == 0 ) {
372 $wgOut->addWikiMsg( 'watchnochange' );
373 return;
374 }
375
376 /* End bottom header */
377
378 /* Do link batch query */
379 $linkBatch = new LinkBatch;
380 foreach ( $res as $row ) {
381 $userNameUnderscored = str_replace( ' ', '_', $row->rc_user_text );
382 if ( $row->rc_user != 0 ) {
383 $linkBatch->add( NS_USER, $userNameUnderscored );
384 }
385 $linkBatch->add( NS_USER_TALK, $userNameUnderscored );
386
387 $linkBatch->add( $row->rc_namespace, $row->rc_title );
388 }
389 $linkBatch->execute();
390 $dbr->dataSeek( $res, 0 );
391
392 $list = ChangesList::newFromUser( $wgUser );
393 $list->setWatchlistDivs();
394
395 $s = $list->beginRecentChangesList();
396 $counter = 1;
397 foreach ( $res as $obj ) {
398 # Make RC entry
399 $rc = RecentChange::newFromRow( $obj );
400 $rc->counter = $counter++;
401
402 if ( $wgShowUpdatedMarker ) {
403 $updated = $obj->wl_notificationtimestamp;
404 } else {
405 $updated = false;
406 }
407
408 if ( $wgRCShowWatchingUsers && $wgUser->getOption( 'shownumberswatching' ) ) {
409 $rc->numberofWatchingusers = $dbr->selectField( 'watchlist',
410 'COUNT(*)',
411 array(
412 'wl_namespace' => $obj->rc_namespace,
413 'wl_title' => $obj->rc_title,
414 ),
415 __METHOD__ );
416 } else {
417 $rc->numberofWatchingusers = 0;
418 }
419
420 $s .= $list->recentChangesLine( $rc, $updated, $counter );
421 }
422 $s .= $list->endRecentChangesList();
423
424 $wgOut->addHTML( $s );
425 }
426
427 public static function showHideLink( $options, $message, $name, $value ) {
428 global $wgUser;
429
430 $showLinktext = wfMsgHtml( 'show' );
431 $hideLinktext = wfMsgHtml( 'hide' );
432 $title = SpecialPage::getTitleFor( 'Watchlist' );
433 $skin = $wgUser->getSkin();
434
435 $label = $value ? $showLinktext : $hideLinktext;
436 $options[$name] = 1 - (int) $value;
437
438 return wfMsgHtml( $message, $skin->linkKnown( $title, $label, array(), $options ) );
439 }
440
441 public static function hoursLink( $h, $page, $options = array() ) {
442 global $wgUser, $wgLang, $wgContLang;
443
444 $sk = $wgUser->getSkin();
445 $title = Title::newFromText( $wgContLang->specialPage( $page ) );
446 $options['days'] = ( $h / 24.0 );
447
448 return $sk->linkKnown(
449 $title,
450 $wgLang->formatNum( $h ),
451 array(),
452 $options
453 );
454 }
455
456 public static function daysLink( $d, $page, $options = array() ) {
457 global $wgUser, $wgLang, $wgContLang;
458
459 $sk = $wgUser->getSkin();
460 $title = Title::newFromText( $wgContLang->specialPage( $page ) );
461 $options['days'] = $d;
462 $message = ( $d ? $wgLang->formatNum( $d ) : wfMsgHtml( 'watchlistall2' ) );
463
464 return $sk->linkKnown(
465 $title,
466 $message,
467 array(),
468 $options
469 );
470 }
471
472 /**
473 * Returns html
474 *
475 * @return string
476 */
477 protected static function cutoffLinks( $days, $page = 'Watchlist', $options = array() ) {
478 global $wgLang;
479
480 $hours = array( 1, 2, 6, 12 );
481 $days = array( 1, 3, 7 );
482 $i = 0;
483 foreach( $hours as $h ) {
484 $hours[$i++] = self::hoursLink( $h, $page, $options );
485 }
486 $i = 0;
487 foreach( $days as $d ) {
488 $days[$i++] = self::daysLink( $d, $page, $options );
489 }
490 return wfMsgExt('wlshowlast',
491 array('parseinline', 'replaceafter'),
492 $wgLang->pipeList( $hours ),
493 $wgLang->pipeList( $days ),
494 self::daysLink( 0, $page, $options ) );
495 }
496
497 /**
498 * Count the number of items on a user's watchlist
499 *
500 * @param $user User object
501 * @param $talk Boolean: include talk pages
502 * @return Integer
503 */
504 protected static function countItems( &$user, $talk = true ) {
505 $dbr = wfGetDB( DB_SLAVE, 'watchlist' );
506
507 # Fetch the raw count
508 $res = $dbr->select( 'watchlist', 'COUNT(*) AS count',
509 array( 'wl_user' => $user->mId ), __METHOD__ );
510 $row = $dbr->fetchObject( $res );
511 $count = $row->count;
512
513 # Halve to remove talk pages if needed
514 if( !$talk ) {
515 $count = floor( $count / 2 );
516 }
517
518 return( $count );
519 }
520 }