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