*Add some IPv6 ranges (64,80,96,112)
[lhc/web/wiklou.git] / includes / SpecialContributions.php
1 <?php
2 /**
3 * @addtogroup SpecialPage
4 */
5
6 class ContribsFinder {
7 var $username, $offset, $limit, $namespace;
8 var $dbr;
9
10 /**
11 * Constructor
12 * @param $username Username as a string
13 */
14 function ContribsFinder( $username ) {
15 $this->username = $username;
16 $this->namespace = false;
17 $this->dbr = wfGetDB( DB_SLAVE, 'contributions' );
18 }
19
20 function setNamespace( $ns ) {
21 $this->namespace = $ns;
22 }
23
24 function setLimit( $limit ) {
25 $this->limit = $limit;
26 }
27
28 function setOffset( $offset ) {
29 $this->offset = $offset;
30 }
31
32 /**
33 * Get timestamp of either first or last contribution made by the user.
34 * @todo Maybe it should be private ?
35 * @param $dir string 'ASC' or 'DESC'.
36 * @return Revision timestamp (rev_timestamp).
37 */
38 function getEditLimit( $dir ) {
39 list( $index, $usercond ) = $this->getUserCond();
40 $nscond = $this->getNamespaceCond();
41 $use_index = $this->dbr->useIndexClause( $index );
42 list( $revision, $page) = $this->dbr->tableNamesN( 'revision', 'page' );
43 $sql = "SELECT rev_timestamp " .
44 " FROM $page,$revision $use_index " .
45 " WHERE rev_page=page_id AND $usercond $nscond" .
46 " ORDER BY rev_timestamp $dir LIMIT 1";
47
48 $res = $this->dbr->query( $sql, __METHOD__ );
49 $row = $this->dbr->fetchObject( $res );
50 if ( $row ) {
51 return $row->rev_timestamp;
52 } else {
53 return false;
54 }
55 }
56
57 /**
58 * Get timestamps of first and last contributions made by the user.
59 * @return Array containing first rev_timestamp and last rev_timestamp.
60 */
61 function getEditLimits() {
62 return array(
63 $this->getEditLimit( "ASC" ),
64 $this->getEditLimit( "DESC" )
65 );
66 }
67
68 function getUserCond() {
69 $condition = '';
70
71 if ( $this->username == 'newbies' ) {
72 $max = $this->dbr->selectField( 'user', 'max(user_id)', false, 'make_sql' );
73 $condition = 'rev_user >' . (int)($max - $max / 100);
74 } else if ( IP::isIPv4( $this->username ) && preg_match("/\/(24|16)$/", $this->username, $matches) ) {
75 $abcd = explode( ".", $this->username );
76 if( $matches[1] == 24 ) $ipmask = $abcd[0] . '.' . $abcd[1] . '.' . $abcd[2] . '.%';
77 else $ipmask=$abcd[0] . '.' . $abcd[1] . '.%';
78 $condition = 'rev_user_text LIKE ' . $this->dbr->addQuotes($ipmask);
79 } else if ( IP::isIPv6( $this->username ) && preg_match("/^(64|80|96|112)$/", $this->username) ) {
80 $abcdefgh = explode( ":", IP::sanitizeIP($this->username) );
81 $abcd = implode( ":", array_slice($abcdefgh, 0, 4) );
82 switch( $matches[1] ) {
83 case '112':
84 $ipmask = $abcd . ':' . $abcd[4] . ':' . $abcd[5] . ':' . $abcd[6] . ':%';
85 break;
86 case '96':
87 $ipmask = $abcd . ':' . $abcd[4] . ':' . $abcd[5] . ':%';
88 break;
89 case '80':
90 $ipmask = $abcd . ':' . $abcd[4] . ':%';
91 break;
92 case '64':
93 $ipmask = $abcd . ':%';
94 break;
95 }
96 $condition = 'rev_user_text LIKE ' . $this->dbr->addQuotes($ipmask);
97 }
98
99 else if ( IP::isIPv6( $this->username ) ) {
100 # All stored IPs should be sanitized from now on, check for exact matches for reverse compatibility
101 $condition = '(rev_user_text=' . $this->dbr->addQuotes(IP::sanitizeIP($this->username)) . ' OR rev_user_text=' . $this->dbr->addQuotes($this->username) . ')';
102 }
103
104 if ( $condition == '' ) {
105 $condition = ' rev_user_text=' . $this->dbr->addQuotes( $this->username );
106 $index = 'usertext_timestamp';
107 } else {
108 #$condition = ' rev_user '.$condition ;
109 $index = 'user_timestamp';
110 }
111 return array( $index, $condition );
112 }
113
114 function getNamespaceCond() {
115 if ( $this->namespace !== false )
116 return ' AND page_namespace = ' . (int)$this->namespace;
117 return '';
118 }
119
120 /**
121 * @return Timestamp of first entry in previous page.
122 */
123 function getPreviousOffsetForPaging() {
124 list( $index, $usercond ) = $this->getUserCond();
125 $nscond = $this->getNamespaceCond();
126
127 $use_index = $this->dbr->useIndexClause( $index );
128 list( $page, $revision ) = $this->dbr->tableNamesN( 'page', 'revision' );
129
130 $sql = "SELECT rev_timestamp FROM $page, $revision $use_index " .
131 "WHERE page_id = rev_page AND rev_timestamp > '" . $this->offset . "' AND " .
132 $usercond . $nscond;
133 $sql .= " ORDER BY rev_timestamp ASC";
134 $sql = $this->dbr->limitResult( $sql, $this->limit, 0 );
135 $res = $this->dbr->query( $sql );
136
137 $numRows = $this->dbr->numRows( $res );
138 if ( $numRows ) {
139 $this->dbr->dataSeek( $res, $numRows - 1 );
140 $row = $this->dbr->fetchObject( $res );
141 $offset = $row->rev_timestamp;
142 } else {
143 $offset = false;
144 }
145 $this->dbr->freeResult( $res );
146 return $offset;
147 }
148
149 /**
150 * @return Timestamp of first entry in next page.
151 */
152 function getFirstOffsetForPaging() {
153 list( $index, $usercond ) = $this->getUserCond();
154 $use_index = $this->dbr->useIndexClause( $index );
155 list( $page, $revision ) = $this->dbr->tableNamesN( 'page', 'revision' );
156 $nscond = $this->getNamespaceCond();
157 $sql = "SELECT rev_timestamp FROM $page, $revision $use_index " .
158 "WHERE page_id = rev_page AND " .
159 $usercond . $nscond;
160 $sql .= " ORDER BY rev_timestamp ASC";
161 $sql = $this->dbr->limitResult( $sql, $this->limit, 0 );
162 $res = $this->dbr->query( $sql );
163
164 $numRows = $this->dbr->numRows( $res );
165 if ( $numRows ) {
166 $this->dbr->dataSeek( $res, $numRows - 1 );
167 $row = $this->dbr->fetchObject( $res );
168 $offset = $row->rev_timestamp;
169 } else {
170 $offset = false;
171 }
172 $this->dbr->freeResult( $res );
173 return $offset;
174 }
175
176 /* private */ function makeSql() {
177 $offsetQuery = '';
178
179 list( $page, $revision ) = $this->dbr->tableNamesN( 'page', 'revision' );
180 list( $index, $userCond ) = $this->getUserCond();
181
182 if ( $this->offset )
183 $offsetQuery = "AND rev_timestamp < '{$this->offset}'";
184
185 $nscond = $this->getNamespaceCond();
186 $use_index = $this->dbr->useIndexClause( $index );
187 $sql = 'SELECT ' .
188 'page_namespace,page_title,page_is_new,page_latest,'.
189 join(',', Revision::selectFields()).
190 " FROM $page,$revision $use_index " .
191 "WHERE page_id=rev_page AND $userCond $nscond $offsetQuery " .
192 'ORDER BY rev_timestamp DESC';
193 $sql = $this->dbr->limitResult( $sql, $this->limit, 0 );
194 return $sql;
195 }
196
197 /**
198 * This do the search for the user given when creating the object.
199 * It should probably be the only public function in this class.
200 * @return Array of contributions.
201 */
202 function find() {
203 $contribs = array();
204 $res = $this->dbr->query( $this->makeSql(), __METHOD__ );
205 while ( $c = $this->dbr->fetchObject( $res ) )
206 $contribs[] = $c;
207 $this->dbr->freeResult( $res );
208 return $contribs;
209 }
210 };
211
212 /**
213 * Special page "user contributions".
214 * Shows a list of the contributions of a user.
215 *
216 * @return none
217 * @param $par String: (optional) user name of the user for which to show the contributions
218 */
219 function wfSpecialContributions( $par = null ) {
220 global $wgUser, $wgOut, $wgLang, $wgRequest;
221
222 $target = isset( $par ) ? $par : $wgRequest->getVal( 'target' );
223 $radiobox = $wgRequest->getVal( 'newbie' );
224
225 // check for radiobox
226 if ( $radiobox == 'contribs-newbie' ) $target = 'newbies';
227
228 if ( !strlen( $target ) ) {
229 $wgOut->addHTML( contributionsForm( '' ) );
230 return;
231 }
232
233 $nt = Title::newFromURL( $target );
234 if ( !$nt ) {
235 $wgOut->addHTML( contributionsForm( '' ) );
236 return;
237 }
238
239 $options = array();
240
241 list( $options['limit'], $options['offset']) = wfCheckLimits();
242 $options['offset'] = $wgRequest->getVal( 'offset' );
243
244 /* Offset must either be numeric, or a "standard" timestamp */
245 $dbr = wfGetDB( DB_SLAVE );
246 if ( !strlen( $options['offset'] )
247 || ($dbr->realTimestamps()
248 && !preg_match ( '/^\d\d\d\d\-\d\d\-\d\d \d\d:\d\d:\d\d(?:[+-]\d\d)?$/', $options['offset'] )
249 )
250 || (!$dbr->realTimestamps()
251 && !preg_match( '/^[0-9]+$/', $options['offset'] )
252 )
253 ) {
254 $options['offset'] = '';
255 }
256
257 $title = SpecialPage::getTitleFor( 'Contributions' );
258 $options['target'] = $target;
259
260 $nt = Title::makeTitle( NS_USER, $nt->getDBkey() );
261 $finder = new ContribsFinder( ( $target == 'newbies' ) ? 'newbies' : $nt->getText() );
262 $finder->setLimit( $options['limit'] );
263 $finder->setOffset( $options['offset'] );
264
265 if ( ( $ns = $wgRequest->getVal( 'namespace', null ) ) !== null && $ns !== '' ) {
266 $options['namespace'] = intval( $ns );
267 $finder->setNamespace( $options['namespace'] );
268 } else {
269 $options['namespace'] = '';
270 }
271
272 if ( $wgUser->isAllowed( 'rollback' ) && $wgRequest->getBool( 'bot' ) ) {
273 $options['bot'] = '1';
274 }
275
276 if ( $wgRequest->getText( 'go' ) == 'prev' ) {
277 $offset = $finder->getPreviousOffsetForPaging();
278 if ( $offset !== false ) {
279 $options['offset'] = $offset;
280 $prevurl = $title->getLocalURL( wfArrayToCGI( $options ) );
281 $wgOut->redirect( $prevurl );
282 return;
283 }
284 }
285
286 if ( $wgRequest->getText( 'go' ) == 'first' && $target != 'newbies') {
287 $offset = $finder->getFirstOffsetForPaging();
288 if ( $offset !== false ) {
289 $options['offset'] = $offset;
290 $prevurl = $title->getLocalURL( wfArrayToCGI( $options ) );
291 $wgOut->redirect( $prevurl );
292 return;
293 }
294 }
295
296 if ( $target == 'newbies' ) {
297 $wgOut->setSubtitle( wfMsgHtml( 'sp-contributions-newbies-sub') );
298 } else if ( preg_match( "/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\/(24|16)/", $target ) ) {
299 $wgOut->setSubtitle( wfMsgHtml( 'contribsub', $target ) );
300 } else {
301 $wgOut->setSubtitle( wfMsgHtml( 'contribsub', contributionsSub( $nt ) ) );
302 }
303
304 $id = User::idFromName( $nt->getText() );
305 wfRunHooks( 'SpecialContributionsBeforeMainOutput', $id );
306
307 $wgOut->addHTML( contributionsForm( $options) );
308
309 $contribs = $finder->find();
310
311 if ( count( $contribs ) == 0) {
312 $wgOut->addWikiText( wfMsg( 'nocontribs' ) );
313 return;
314 }
315
316 list( $early, $late ) = $finder->getEditLimits();
317 $lastts = count( $contribs ) ? $contribs[count( $contribs ) - 1]->rev_timestamp : 0;
318 $atstart = ( !count( $contribs ) || $late == $contribs[0]->rev_timestamp );
319 $atend = ( !count( $contribs ) || $early == $lastts );
320
321 // These four are defaults
322 $newestlink = wfMsgHtml( 'sp-contributions-newest' );
323 $oldestlink = wfMsgHtml( 'sp-contributions-oldest' );
324 $newerlink = wfMsgHtml( 'sp-contributions-newer', $options['limit'] );
325 $olderlink = wfMsgHtml( 'sp-contributions-older', $options['limit'] );
326
327 if ( !$atstart ) {
328 $stuff = $title->escapeLocalURL( wfArrayToCGI( array( 'offset' => '' ), $options ) );
329 $newestlink = "<a href=\"$stuff\">$newestlink</a>";
330 $stuff = $title->escapeLocalURL( wfArrayToCGI( array( 'go' => 'prev' ), $options ) );
331 $newerlink = "<a href=\"$stuff\">$newerlink</a>";
332 }
333
334 if ( !$atend ) {
335 $stuff = $title->escapeLocalURL( wfArrayToCGI( array( 'go' => 'first' ), $options ) );
336 $oldestlink = "<a href=\"$stuff\">$oldestlink</a>";
337 $stuff = $title->escapeLocalURL( wfArrayToCGI( array( 'offset' => $lastts ), $options ) );
338 $olderlink = "<a href=\"$stuff\">$olderlink</a>";
339 }
340
341 if ( $target == 'newbies' ) {
342 $firstlast ="($newestlink)";
343 } else {
344 $firstlast = "($newestlink | $oldestlink)";
345 }
346
347 $urls = array();
348 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
349 $stuff = $title->escapeLocalURL( wfArrayToCGI( array( 'limit' => $num ), $options ) );
350 $urls[] = "<a href=\"$stuff\">".$wgLang->formatNum( $num )."</a>";
351 }
352 $bits = implode( $urls, ' | ' );
353
354 $prevnextbits = $firstlast .' '. wfMsgHtml( 'viewprevnext', $newerlink, $olderlink, $bits );
355
356 $wgOut->addHTML( "<p>{$prevnextbits}</p>\n" );
357
358 $wgOut->addHTML( "<ul>\n" );
359
360 $sk = $wgUser->getSkin();
361 foreach ( $contribs as $contrib )
362 $wgOut->addHTML( ucListEdit( $sk, $contrib ) );
363
364 $wgOut->addHTML( "</ul>\n" );
365 $wgOut->addHTML( "<p>{$prevnextbits}</p>\n" );
366 }
367
368 /**
369 * Generates the subheading with links
370 * @param $nt @see Title object for the target
371 */
372 function contributionsSub( $nt ) {
373 global $wgSysopUserBans, $wgLang, $wgUser;
374
375 $sk = $wgUser->getSkin();
376 $id = User::idFromName( $nt->getText() );
377
378 if ( 0 == $id ) {
379 $ul = $nt->getText();
380 } else {
381 $ul = $sk->makeLinkObj( $nt, htmlspecialchars( $nt->getText() ) );
382 }
383 $talk = $nt->getTalkPage();
384 if( $talk ) {
385 # Talk page link
386 $tools[] = $sk->makeLinkObj( $talk, $wgLang->getNsText( NS_TALK ) );
387 if( ( $id != 0 && $wgSysopUserBans ) || ( $id == 0 && User::isIP( $nt->getText() ) ) ) {
388 # Block link
389 if( $wgUser->isAllowed( 'block' ) )
390 $tools[] = $sk->makeKnownLinkObj( SpecialPage::getTitleFor( 'Blockip', $nt->getDBkey() ), wfMsgHtml( 'blocklink' ) );
391 # Block log link
392 $tools[] = $sk->makeKnownLinkObj( SpecialPage::getTitleFor( 'Log' ), wfMsgHtml( 'sp-contributions-blocklog' ), 'type=block&page=' . $nt->getPrefixedUrl() );
393 }
394 # Other logs link
395 $tools[] = $sk->makeKnownLinkObj( SpecialPage::getTitleFor( 'Log' ), wfMsgHtml( 'log' ), 'user=' . $nt->getPartialUrl() );
396 $ul .= ' (' . implode( ' | ', $tools ) . ')';
397 }
398 return $ul;
399 }
400
401 /**
402 * Generates the namespace selector form with hidden attributes.
403 * @param $options Array: the options to be included.
404 */
405 function contributionsForm( $options ) {
406 global $wgScript, $wgTitle, $wgRequest;
407
408 $options['title'] = $wgTitle->getPrefixedText();
409 if (!isset($options['target']))
410 $options['target'] = '';
411 if (!isset($options['namespace']))
412 $options['namespace'] = 0;
413
414 $f = Xml::openElement( 'form', array( 'method' => 'get', 'action' => $wgScript ) );
415
416 foreach ( $options as $name => $value ) {
417 if( $name === 'namespace') continue;
418 $f .= "\t" . Xml::hidden( $name, $value ) . "\n";
419 }
420
421 $f .= '<fieldset>' .
422 Xml::element( 'legend', array(), wfMsg( 'sp-contributions-search' ) ) .
423 Xml::radioLabel( wfMsgExt( 'sp-contributions-newbies', array( 'parseinline' ) ), 'newbie' , 'contribs-newbie' , 'contribs-newbie', 'contribs-newbie' ) . '<br />' .
424 Xml::radioLabel( wfMsgExt( 'sp-contributions-username', array( 'parseinline' ) ), 'newbie' , 'contribs-all', 'contribs-all', 'contribs-all' ) . ' ' .
425 Xml::input( 'target', 20, $options['target']) . ' '.
426 Xml::label( wfMsg( 'namespace' ), 'namespace' ) .
427 Xml::namespaceSelector( $options['namespace'], '' ) .
428 Xml::submitButton( wfMsg( 'sp-contributions-submit' ) ) .
429 '</fieldset>' .
430 Xml::closeElement( 'form' );
431 return $f;
432 }
433
434 /**
435 * Generates each row in the contributions list.
436 *
437 * Contributions which are marked "top" are currently on top of the history.
438 * For these contributions, a [rollback] link is shown for users with sysop
439 * privileges. The rollback link restores the most recent version that was not
440 * written by the target user.
441 *
442 * @todo This would probably look a lot nicer in a table.
443 */
444 function ucListEdit( $sk, $row ) {
445 $fname = 'ucListEdit';
446 wfProfileIn( $fname );
447
448 global $wgLang, $wgUser, $wgRequest;
449 static $messages;
450 if( !isset( $messages ) ) {
451 foreach( explode( ' ', 'uctop diff newarticle rollbacklink diff hist minoreditletter' ) as $msg ) {
452 $messages[$msg] = wfMsgExt( $msg, array( 'escape') );
453 }
454 }
455
456 $rev = new Revision( $row );
457
458 $page = Title::makeTitle( $row->page_namespace, $row->page_title );
459 $link = $sk->makeKnownLinkObj( $page );
460 $difftext = $topmarktext = '';
461 if( $row->rev_id == $row->page_latest ) {
462 $topmarktext .= '<strong>' . $messages['uctop'] . '</strong>';
463 if( !$row->page_is_new ) {
464 $difftext .= '(' . $sk->makeKnownLinkObj( $page, $messages['diff'], 'diff=0' ) . ')';
465 } else {
466 $difftext .= $messages['newarticle'];
467 }
468
469 if( $wgUser->isAllowed( 'rollback' ) ) {
470 $topmarktext .= ' '.$sk->generateRollback( $rev );
471 }
472
473 }
474 if( $rev->userCan( Revision::DELETED_TEXT ) ) {
475 $difftext = '(' . $sk->makeKnownLinkObj( $page, $messages['diff'], 'diff=prev&oldid='.$row->rev_id ) . ')';
476 } else {
477 $difftext = '(' . $messages['diff'] . ')';
478 }
479 $histlink='('.$sk->makeKnownLinkObj( $page, $messages['hist'], 'action=history' ) . ')';
480
481 $comment = $sk->revComment( $rev );
482 $d = $wgLang->timeanddate( wfTimestamp( TS_MW, $row->rev_timestamp ), true );
483
484 if( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
485 $d = '<span class="history-deleted">' . $d . '</span>';
486 }
487
488 if( $row->rev_minor_edit ) {
489 $mflag = '<span class="minor">' . $messages['minoreditletter'] . '</span> ';
490 } else {
491 $mflag = '';
492 }
493
494 $ret = "{$d} {$histlink} {$difftext} {$mflag} {$link} {$comment} {$topmarktext}";
495 if( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
496 $ret .= ' ' . wfMsgHtml( 'deletedrev' );
497 }
498 $ret = "<li>$ret</li>\n";
499 wfProfileOut( $fname );
500 return $ret;
501 }
502
503 ?>