Merge "API: HTMLize and internationalize the help, add Special:ApiHelp"
[lhc/web/wiklou.git] / includes / specials / SpecialContributions.php
1 <?php
2 /**
3 * Implements Special:Contributions
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 * Special:Contributions, show user contributions in a paged list
26 *
27 * @ingroup SpecialPage
28 */
29 class SpecialContributions extends IncludableSpecialPage {
30 protected $opts;
31
32 public function __construct() {
33 parent::__construct( 'Contributions' );
34 }
35
36 public function execute( $par ) {
37 $this->setHeaders();
38 $this->outputHeader();
39 $out = $this->getOutput();
40 $out->addModuleStyles( 'mediawiki.special' );
41
42 $this->opts = array();
43 $request = $this->getRequest();
44
45 if ( $par !== null ) {
46 $target = $par;
47 } else {
48 $target = $request->getVal( 'target' );
49 }
50
51 // check for radiobox
52 if ( $request->getVal( 'contribs' ) == 'newbie' ) {
53 $target = 'newbies';
54 $this->opts['contribs'] = 'newbie';
55 } elseif ( $par === 'newbies' ) { // b/c for WMF
56 $target = 'newbies';
57 $this->opts['contribs'] = 'newbie';
58 } else {
59 $this->opts['contribs'] = 'user';
60 }
61
62 $this->opts['deletedOnly'] = $request->getBool( 'deletedOnly' );
63
64 if ( !strlen( $target ) ) {
65 if ( !$this->including() ) {
66 $out->addHTML( $this->getForm() );
67 }
68
69 return;
70 }
71
72 $user = $this->getUser();
73
74 $this->opts['limit'] = $request->getInt( 'limit', $user->getOption( 'rclimit' ) );
75 $this->opts['target'] = $target;
76 $this->opts['topOnly'] = $request->getBool( 'topOnly' );
77 $this->opts['newOnly'] = $request->getBool( 'newOnly' );
78
79 $nt = Title::makeTitleSafe( NS_USER, $target );
80 if ( !$nt ) {
81 $out->addHTML( $this->getForm() );
82
83 return;
84 }
85 $userObj = User::newFromName( $nt->getText(), false );
86 if ( !$userObj ) {
87 $out->addHTML( $this->getForm() );
88
89 return;
90 }
91 $id = $userObj->getID();
92
93 if ( $this->opts['contribs'] != 'newbie' ) {
94 $target = $nt->getText();
95 $out->addSubtitle( $this->contributionsSub( $userObj ) );
96 $out->setHTMLTitle( $this->msg(
97 'pagetitle',
98 $this->msg( 'contributions-title', $target )->plain()
99 )->inContentLanguage() );
100 $this->getSkin()->setRelevantUser( $userObj );
101 } else {
102 $out->addSubtitle( $this->msg( 'sp-contributions-newbies-sub' ) );
103 $out->setHTMLTitle( $this->msg(
104 'pagetitle',
105 $this->msg( 'sp-contributions-newbies-title' )->plain()
106 )->inContentLanguage() );
107 }
108
109 if ( ( $ns = $request->getVal( 'namespace', null ) ) !== null && $ns !== '' ) {
110 $this->opts['namespace'] = intval( $ns );
111 } else {
112 $this->opts['namespace'] = '';
113 }
114
115 $this->opts['associated'] = $request->getBool( 'associated' );
116 $this->opts['nsInvert'] = (bool)$request->getVal( 'nsInvert' );
117 $this->opts['tagfilter'] = (string)$request->getVal( 'tagfilter' );
118
119 // Allows reverts to have the bot flag in recent changes. It is just here to
120 // be passed in the form at the top of the page
121 if ( $user->isAllowed( 'markbotedits' ) && $request->getBool( 'bot' ) ) {
122 $this->opts['bot'] = '1';
123 }
124
125 $skip = $request->getText( 'offset' ) || $request->getText( 'dir' ) == 'prev';
126 # Offset overrides year/month selection
127 if ( $skip ) {
128 $this->opts['year'] = '';
129 $this->opts['month'] = '';
130 } else {
131 $this->opts['year'] = $request->getIntOrNull( 'year' );
132 $this->opts['month'] = $request->getIntOrNull( 'month' );
133 }
134
135 $feedType = $request->getVal( 'feed' );
136
137 $feedParams = array(
138 'action' => 'feedcontributions',
139 'user' => $target,
140 );
141 if ( $this->opts['topOnly'] ) {
142 $feedParams['toponly'] = true;
143 }
144 if ( $this->opts['newOnly'] ) {
145 $feedParams['newonly'] = true;
146 }
147 if ( $this->opts['deletedOnly'] ) {
148 $feedParams['deletedonly'] = true;
149 }
150 if ( $this->opts['tagfilter'] !== '' ) {
151 $feedParams['tagfilter'] = $this->opts['tagfilter'];
152 }
153 if ( $this->opts['namespace'] !== '' ) {
154 $feedParams['namespace'] = $this->opts['namespace'];
155 }
156 // Don't use year and month for the feed URL, but pass them on if
157 // we redirect to API (if $feedType is specified)
158 if ( $feedType && $this->opts['year'] !== null ) {
159 $feedParams['year'] = $this->opts['year'];
160 }
161 if ( $feedType && $this->opts['month'] !== null ) {
162 $feedParams['month'] = $this->opts['month'];
163 }
164
165 if ( $feedType ) {
166 // Maintain some level of backwards compatibility
167 // If people request feeds using the old parameters, redirect to API
168 $feedParams['feedformat'] = $feedType;
169 $url = wfAppendQuery( wfScript( 'api' ), $feedParams );
170
171 $out->redirect( $url, '301' );
172
173 return;
174 }
175
176 // Add RSS/atom links
177 $this->addFeedLinks( $feedParams );
178
179 if ( wfRunHooks( 'SpecialContributionsBeforeMainOutput', array( $id, $userObj, $this ) ) ) {
180 if ( !$this->including() ) {
181 $out->addHTML( $this->getForm() );
182 }
183 $pager = new ContribsPager( $this->getContext(), array(
184 'target' => $target,
185 'contribs' => $this->opts['contribs'],
186 'namespace' => $this->opts['namespace'],
187 'tagfilter' => $this->opts['tagfilter'],
188 'year' => $this->opts['year'],
189 'month' => $this->opts['month'],
190 'deletedOnly' => $this->opts['deletedOnly'],
191 'topOnly' => $this->opts['topOnly'],
192 'newOnly' => $this->opts['newOnly'],
193 'nsInvert' => $this->opts['nsInvert'],
194 'associated' => $this->opts['associated'],
195 ) );
196
197 if ( !$pager->getNumRows() ) {
198 $out->addWikiMsg( 'nocontribs', $target );
199 } else {
200 # Show a message about slave lag, if applicable
201 $lag = wfGetLB()->safeGetLag( $pager->getDatabase() );
202 if ( $lag > 0 ) {
203 $out->showLagWarning( $lag );
204 }
205
206 $output = $pager->getBody();
207 if ( !$this->including() ) {
208 $output = '<p>' . $pager->getNavigationBar() . '</p>' .
209 $output .
210 '<p>' . $pager->getNavigationBar() . '</p>';
211 }
212 $out->addHTML( $output );
213 }
214 $out->preventClickjacking( $pager->getPreventClickjacking() );
215
216 # Show the appropriate "footer" message - WHOIS tools, etc.
217 if ( $this->opts['contribs'] == 'newbie' ) {
218 $message = 'sp-contributions-footer-newbies';
219 } elseif ( IP::isIPAddress( $target ) ) {
220 $message = 'sp-contributions-footer-anon';
221 } elseif ( $userObj->isAnon() ) {
222 // No message for non-existing users
223 $message = '';
224 } else {
225 $message = 'sp-contributions-footer';
226 }
227
228 if ( $message ) {
229 if ( !$this->including() ) {
230 if ( !$this->msg( $message, $target )->isDisabled() ) {
231 $out->wrapWikiMsg(
232 "<div class='mw-contributions-footer'>\n$1\n</div>",
233 array( $message, $target ) );
234 }
235 }
236 }
237 }
238 }
239
240 /**
241 * Generates the subheading with links
242 * @param User $userObj User object for the target
243 * @return string Appropriately-escaped HTML to be output literally
244 * @todo FIXME: Almost the same as getSubTitle in SpecialDeletedContributions.php.
245 * Could be combined.
246 */
247 protected function contributionsSub( $userObj ) {
248 if ( $userObj->isAnon() ) {
249 // Show a warning message that the user being searched for doesn't exists
250 if ( !User::isIP( $userObj->getName() ) ) {
251 $this->getOutput()->wrapWikiMsg(
252 "<div class=\"mw-userpage-userdoesnotexist error\">\n\$1\n</div>",
253 array(
254 'contributions-userdoesnotexist',
255 wfEscapeWikiText( $userObj->getName() ),
256 )
257 );
258 if ( !$this->including() ) {
259 $this->getOutput()->setStatusCode( 404 );
260 }
261 }
262 $user = htmlspecialchars( $userObj->getName() );
263 } else {
264 $user = Linker::link( $userObj->getUserPage(), htmlspecialchars( $userObj->getName() ) );
265 }
266 $nt = $userObj->getUserPage();
267 $talk = $userObj->getTalkPage();
268 $links = '';
269 if ( $talk ) {
270 $tools = $this->getUserLinks( $nt, $talk, $userObj );
271 $links = $this->getLanguage()->pipeList( $tools );
272
273 // Show a note if the user is blocked and display the last block log entry.
274 // Do not expose the autoblocks, since that may lead to a leak of accounts' IPs,
275 // and also this will display a totally irrelevant log entry as a current block.
276 if ( !$this->including() ) {
277 $block = Block::newFromTarget( $userObj, $userObj );
278 if ( !is_null( $block ) && $block->getType() != Block::TYPE_AUTO ) {
279 if ( $block->getType() == Block::TYPE_RANGE ) {
280 $nt = MWNamespace::getCanonicalName( NS_USER ) . ':' . $block->getTarget();
281 }
282
283 $out = $this->getOutput(); // showLogExtract() wants first parameter by reference
284 LogEventsList::showLogExtract(
285 $out,
286 'block',
287 $nt,
288 '',
289 array(
290 'lim' => 1,
291 'showIfEmpty' => false,
292 'msgKey' => array(
293 $userObj->isAnon() ?
294 'sp-contributions-blocked-notice-anon' :
295 'sp-contributions-blocked-notice',
296 $userObj->getName() # Support GENDER in 'sp-contributions-blocked-notice'
297 ),
298 'offset' => '' # don't use WebRequest parameter offset
299 )
300 );
301 }
302 }
303 }
304
305 return $this->msg( 'contribsub2' )->rawParams( $user, $links )->params( $userObj->getName() );
306 }
307
308 /**
309 * Links to different places.
310 * @param Title $userpage Target user page
311 * @param Title $talkpage Talk page
312 * @param User $target Target user object
313 * @return array
314 */
315 public function getUserLinks( Title $userpage, Title $talkpage, User $target ) {
316
317 $id = $target->getId();
318 $username = $target->getName();
319
320 $tools[] = Linker::link( $talkpage, $this->msg( 'sp-contributions-talk' )->escaped() );
321
322 if ( ( $id !== null ) || ( $id === null && IP::isIPAddress( $username ) ) ) {
323 if ( $this->getUser()->isAllowed( 'block' ) ) { # Block / Change block / Unblock links
324 if ( $target->isBlocked() && $target->getBlock()->getType() != Block::TYPE_AUTO ) {
325 $tools[] = Linker::linkKnown( # Change block link
326 SpecialPage::getTitleFor( 'Block', $username ),
327 $this->msg( 'change-blocklink' )->escaped()
328 );
329 $tools[] = Linker::linkKnown( # Unblock link
330 SpecialPage::getTitleFor( 'Unblock', $username ),
331 $this->msg( 'unblocklink' )->escaped()
332 );
333 } else { # User is not blocked
334 $tools[] = Linker::linkKnown( # Block link
335 SpecialPage::getTitleFor( 'Block', $username ),
336 $this->msg( 'blocklink' )->escaped()
337 );
338 }
339 }
340
341 # Block log link
342 $tools[] = Linker::linkKnown(
343 SpecialPage::getTitleFor( 'Log', 'block' ),
344 $this->msg( 'sp-contributions-blocklog' )->escaped(),
345 array(),
346 array( 'page' => $userpage->getPrefixedText() )
347 );
348
349 # Suppression log link (bug 59120)
350 if ( $this->getUser()->isAllowed( 'suppressionlog' ) ) {
351 $tools[] = Linker::linkKnown(
352 SpecialPage::getTitleFor( 'Log', 'suppress' ),
353 $this->msg( 'sp-contributions-suppresslog' )->escaped(),
354 array(),
355 array( 'offender' => $username )
356 );
357 }
358 }
359 # Uploads
360 $tools[] = Linker::linkKnown(
361 SpecialPage::getTitleFor( 'Listfiles', $username ),
362 $this->msg( 'sp-contributions-uploads' )->escaped()
363 );
364
365 # Other logs link
366 $tools[] = Linker::linkKnown(
367 SpecialPage::getTitleFor( 'Log', $username ),
368 $this->msg( 'sp-contributions-logs' )->escaped()
369 );
370
371 # Add link to deleted user contributions for priviledged users
372 if ( $this->getUser()->isAllowed( 'deletedhistory' ) ) {
373 $tools[] = Linker::linkKnown(
374 SpecialPage::getTitleFor( 'DeletedContributions', $username ),
375 $this->msg( 'sp-contributions-deleted' )->escaped()
376 );
377 }
378
379 # Add a link to change user rights for privileged users
380 $userrightsPage = new UserrightsPage();
381 $userrightsPage->setContext( $this->getContext() );
382 if ( $userrightsPage->userCanChangeRights( $target ) ) {
383 $tools[] = Linker::linkKnown(
384 SpecialPage::getTitleFor( 'Userrights', $username ),
385 $this->msg( 'sp-contributions-userrights' )->escaped()
386 );
387 }
388
389 wfRunHooks( 'ContributionsToolLinks', array( $id, $userpage, &$tools ) );
390
391 return $tools;
392 }
393
394 /**
395 * Generates the namespace selector form with hidden attributes.
396 * @return string HTML fragment
397 */
398 protected function getForm() {
399 $this->opts['title'] = $this->getPageTitle()->getPrefixedText();
400 if ( !isset( $this->opts['target'] ) ) {
401 $this->opts['target'] = '';
402 } else {
403 $this->opts['target'] = str_replace( '_', ' ', $this->opts['target'] );
404 }
405
406 if ( !isset( $this->opts['namespace'] ) ) {
407 $this->opts['namespace'] = '';
408 }
409
410 if ( !isset( $this->opts['nsInvert'] ) ) {
411 $this->opts['nsInvert'] = '';
412 }
413
414 if ( !isset( $this->opts['associated'] ) ) {
415 $this->opts['associated'] = false;
416 }
417
418 if ( !isset( $this->opts['contribs'] ) ) {
419 $this->opts['contribs'] = 'user';
420 }
421
422 if ( !isset( $this->opts['year'] ) ) {
423 $this->opts['year'] = '';
424 }
425
426 if ( !isset( $this->opts['month'] ) ) {
427 $this->opts['month'] = '';
428 }
429
430 if ( $this->opts['contribs'] == 'newbie' ) {
431 $this->opts['target'] = '';
432 }
433
434 if ( !isset( $this->opts['tagfilter'] ) ) {
435 $this->opts['tagfilter'] = '';
436 }
437
438 if ( !isset( $this->opts['topOnly'] ) ) {
439 $this->opts['topOnly'] = false;
440 }
441
442 if ( !isset( $this->opts['newOnly'] ) ) {
443 $this->opts['newOnly'] = false;
444 }
445
446 $form = Html::openElement(
447 'form',
448 array(
449 'method' => 'get',
450 'action' => wfScript(),
451 'class' => 'mw-contributions-form'
452 )
453 );
454
455 # Add hidden params for tracking except for parameters in $skipParameters
456 $skipParameters = array(
457 'namespace',
458 'nsInvert',
459 'deletedOnly',
460 'target',
461 'contribs',
462 'year',
463 'month',
464 'topOnly',
465 'newOnly',
466 'associated'
467 );
468
469 foreach ( $this->opts as $name => $value ) {
470 if ( in_array( $name, $skipParameters ) ) {
471 continue;
472 }
473 $form .= "\t" . Html::hidden( $name, $value ) . "\n";
474 }
475
476 $tagFilter = ChangeTags::buildTagFilterSelector( $this->opts['tagfilter'] );
477
478 if ( $tagFilter ) {
479 $filterSelection = Html::rawElement(
480 'td',
481 array(),
482 array_shift( $tagFilter ) . implode( '&#160', $tagFilter )
483 );
484 } else {
485 $filterSelection = Html::rawElement( 'td', array( 'colspan' => 2 ), '' );
486 }
487
488 $labelNewbies = Xml::radioLabel(
489 $this->msg( 'sp-contributions-newbies' )->text(),
490 'contribs',
491 'newbie',
492 'newbie',
493 $this->opts['contribs'] == 'newbie',
494 array( 'class' => 'mw-input' )
495 );
496 $labelUsername = Xml::radioLabel(
497 $this->msg( 'sp-contributions-username' )->text(),
498 'contribs',
499 'user',
500 'user',
501 $this->opts['contribs'] == 'user',
502 array( 'class' => 'mw-input' )
503 );
504 $input = Html::input(
505 'target',
506 $this->opts['target'],
507 'text',
508 array( 'size' => '40', 'required' => '', 'class' => 'mw-input mw-ui-input-inline' ) +
509 ( $this->opts['target'] ? array() : array( 'autofocus' )
510 )
511 );
512 $targetSelection = Html::rawElement(
513 'td',
514 array( 'colspan' => 2 ),
515 $labelNewbies . '<br />' . $labelUsername . ' ' . $input . ' '
516 );
517
518 $namespaceSelection = Xml::tags(
519 'td',
520 array(),
521 Xml::label(
522 $this->msg( 'namespace' )->text(),
523 'namespace',
524 ''
525 ) .
526 Html::namespaceSelector(
527 array( 'selected' => $this->opts['namespace'], 'all' => '' ),
528 array(
529 'name' => 'namespace',
530 'id' => 'namespace',
531 'class' => 'namespaceselector',
532 )
533 ) . '&#160;' .
534 Html::rawElement(
535 'span',
536 array( 'style' => 'white-space: nowrap' ),
537 Xml::checkLabel(
538 $this->msg( 'invert' )->text(),
539 'nsInvert',
540 'nsInvert',
541 $this->opts['nsInvert'],
542 array(
543 'title' => $this->msg( 'tooltip-invert' )->text(),
544 'class' => 'mw-input'
545 )
546 ) . '&#160;'
547 ) .
548 Html::rawElement( 'span', array( 'style' => 'white-space: nowrap' ),
549 Xml::checkLabel(
550 $this->msg( 'namespace_association' )->text(),
551 'associated',
552 'associated',
553 $this->opts['associated'],
554 array(
555 'title' => $this->msg( 'tooltip-namespace_association' )->text(),
556 'class' => 'mw-input'
557 )
558 ) . '&#160;'
559 )
560 );
561
562 if ( $this->getUser()->isAllowed( 'deletedhistory' ) ) {
563 $deletedOnlyCheck = Html::rawElement(
564 'span',
565 array( 'style' => 'white-space: nowrap' ),
566 Xml::checkLabel(
567 $this->msg( 'history-show-deleted' )->text(),
568 'deletedOnly',
569 'mw-show-deleted-only',
570 $this->opts['deletedOnly'],
571 array( 'class' => 'mw-input' )
572 )
573 );
574 } else {
575 $deletedOnlyCheck = '';
576 }
577
578 $checkLabelTopOnly = Html::rawElement(
579 'span',
580 array( 'style' => 'white-space: nowrap' ),
581 Xml::checkLabel(
582 $this->msg( 'sp-contributions-toponly' )->text(),
583 'topOnly',
584 'mw-show-top-only',
585 $this->opts['topOnly'],
586 array( 'class' => 'mw-input' )
587 )
588 );
589 $checkLabelNewOnly = Html::rawElement(
590 'span',
591 array( 'style' => 'white-space: nowrap' ),
592 Xml::checkLabel(
593 $this->msg( 'sp-contributions-newonly' )->text(),
594 'newOnly',
595 'mw-show-new-only',
596 $this->opts['newOnly'],
597 array( 'class' => 'mw-input' )
598 )
599 );
600 $extraOptions = Html::rawElement(
601 'td',
602 array( 'colspan' => 2 ),
603 $deletedOnlyCheck . $checkLabelTopOnly . $checkLabelNewOnly
604 );
605
606 $dateSelectionAndSubmit = Xml::tags( 'td', array( 'colspan' => 2 ),
607 Xml::dateMenu(
608 $this->opts['year'] === '' ? MWTimestamp::getInstance()->format( 'Y' ) : $this->opts['year'],
609 $this->opts['month']
610 ) . ' ' .
611 Html::submitButton(
612 $this->msg( 'sp-contributions-submit' )->text(),
613 array( 'class' => 'mw-submit' ), array( 'mw-ui-progressive' )
614 )
615 );
616
617 $form .= Xml::fieldset( $this->msg( 'sp-contributions-search' )->text() );
618 $form .= Html::rawElement( 'table', array( 'class' => 'mw-contributions-table' ), "\n" .
619 Html::rawElement( 'tr', array(), $targetSelection ) . "\n" .
620 Html::rawElement( 'tr', array(), $namespaceSelection ) . "\n" .
621 Html::rawElement( 'tr', array(), $filterSelection ) . "\n" .
622 Html::rawElement( 'tr', array(), $extraOptions ) . "\n" .
623 Html::rawElement( 'tr', array(), $dateSelectionAndSubmit ) . "\n"
624 );
625
626 $explain = $this->msg( 'sp-contributions-explain' );
627 if ( !$explain->isBlank() ) {
628 $form .= "<p id='mw-sp-contributions-explain'>{$explain->parse()}</p>";
629 }
630
631 $form .= Xml::closeElement( 'fieldset' ) . Xml::closeElement( 'form' );
632
633 return $form;
634 }
635
636 protected function getGroupName() {
637 return 'users';
638 }
639 }
640
641 /**
642 * Pager for Special:Contributions
643 * @ingroup SpecialPage Pager
644 */
645 class ContribsPager extends ReverseChronologicalPager {
646 public $mDefaultDirection = IndexPager::DIR_DESCENDING;
647 public $messages;
648 public $target;
649 public $namespace = '';
650 public $mDb;
651 public $preventClickjacking = false;
652
653 /** @var DatabaseBase */
654 public $mDbSecondary;
655
656 /**
657 * @var array
658 */
659 protected $mParentLens;
660
661 function __construct( IContextSource $context, array $options ) {
662 parent::__construct( $context );
663
664 $msgs = array(
665 'diff',
666 'hist',
667 'newarticle',
668 'pipe-separator',
669 'rev-delundel',
670 'rollbacklink',
671 'uctop'
672 );
673
674 foreach ( $msgs as $msg ) {
675 $this->messages[$msg] = $this->msg( $msg )->escaped();
676 }
677
678 $this->target = isset( $options['target'] ) ? $options['target'] : '';
679 $this->contribs = isset( $options['contribs'] ) ? $options['contribs'] : 'users';
680 $this->namespace = isset( $options['namespace'] ) ? $options['namespace'] : '';
681 $this->tagFilter = isset( $options['tagfilter'] ) ? $options['tagfilter'] : false;
682 $this->nsInvert = isset( $options['nsInvert'] ) ? $options['nsInvert'] : false;
683 $this->associated = isset( $options['associated'] ) ? $options['associated'] : false;
684
685 $this->deletedOnly = !empty( $options['deletedOnly'] );
686 $this->topOnly = !empty( $options['topOnly'] );
687 $this->newOnly = !empty( $options['newOnly'] );
688
689 $year = isset( $options['year'] ) ? $options['year'] : false;
690 $month = isset( $options['month'] ) ? $options['month'] : false;
691 $this->getDateCond( $year, $month );
692
693 // Most of this code will use the 'contributions' group DB, which can map to slaves
694 // with extra user based indexes or partioning by user. The additional metadata
695 // queries should use a regular slave since the lookup pattern is not all by user.
696 $this->mDbSecondary = wfGetDB( DB_SLAVE ); // any random slave
697 $this->mDb = wfGetDB( DB_SLAVE, 'contributions' );
698 }
699
700 function getDefaultQuery() {
701 $query = parent::getDefaultQuery();
702 $query['target'] = $this->target;
703
704 return $query;
705 }
706
707 /**
708 * This method basically executes the exact same code as the parent class, though with
709 * a hook added, to allow extentions to add additional queries.
710 *
711 * @param string $offset Index offset, inclusive
712 * @param int $limit Exact query limit
713 * @param bool $descending Query direction, false for ascending, true for descending
714 * @return ResultWrapper
715 */
716 function reallyDoQuery( $offset, $limit, $descending ) {
717 list( $tables, $fields, $conds, $fname, $options, $join_conds ) = $this->buildQueryInfo(
718 $offset,
719 $limit,
720 $descending
721 );
722 $pager = $this;
723
724 /*
725 * This hook will allow extensions to add in additional queries, so they can get their data
726 * in My Contributions as well. Extensions should append their results to the $data array.
727 *
728 * Extension queries have to implement the navbar requirement as well. They should
729 * - have a column aliased as $pager->getIndexField()
730 * - have LIMIT set
731 * - have a WHERE-clause that compares the $pager->getIndexField()-equivalent column to the offset
732 * - have the ORDER BY specified based upon the details provided by the navbar
733 *
734 * See includes/Pager.php buildQueryInfo() method on how to build LIMIT, WHERE & ORDER BY
735 *
736 * &$data: an array of results of all contribs queries
737 * $pager: the ContribsPager object hooked into
738 * $offset: see phpdoc above
739 * $limit: see phpdoc above
740 * $descending: see phpdoc above
741 */
742 $data = array( $this->mDb->select(
743 $tables, $fields, $conds, $fname, $options, $join_conds
744 ) );
745 wfRunHooks(
746 'ContribsPager::reallyDoQuery',
747 array( &$data, $pager, $offset, $limit, $descending )
748 );
749
750 $result = array();
751
752 // loop all results and collect them in an array
753 foreach ( $data as $query ) {
754 foreach ( $query as $i => $row ) {
755 // use index column as key, allowing us to easily sort in PHP
756 $result[$row->{$this->getIndexField()} . "-$i"] = $row;
757 }
758 }
759
760 // sort results
761 if ( $descending ) {
762 ksort( $result );
763 } else {
764 krsort( $result );
765 }
766
767 // enforce limit
768 $result = array_slice( $result, 0, $limit );
769
770 // get rid of array keys
771 $result = array_values( $result );
772
773 return new FakeResultWrapper( $result );
774 }
775
776 function getQueryInfo() {
777 list( $tables, $index, $userCond, $join_cond ) = $this->getUserCond();
778
779 $user = $this->getUser();
780 $conds = array_merge( $userCond, $this->getNamespaceCond() );
781
782 // Paranoia: avoid brute force searches (bug 17342)
783 if ( !$user->isAllowed( 'deletedhistory' ) ) {
784 $conds[] = $this->mDb->bitAnd( 'rev_deleted', Revision::DELETED_USER ) . ' = 0';
785 } elseif ( !$user->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
786 $conds[] = $this->mDb->bitAnd( 'rev_deleted', Revision::SUPPRESSED_USER ) .
787 ' != ' . Revision::SUPPRESSED_USER;
788 }
789
790 # Don't include orphaned revisions
791 $join_cond['page'] = Revision::pageJoinCond();
792 # Get the current user name for accounts
793 $join_cond['user'] = Revision::userJoinCond();
794
795 $options = array();
796 if ( $index ) {
797 $options['USE INDEX'] = array( 'revision' => $index );
798 }
799
800 $queryInfo = array(
801 'tables' => $tables,
802 'fields' => array_merge(
803 Revision::selectFields(),
804 Revision::selectUserFields(),
805 array( 'page_namespace', 'page_title', 'page_is_new',
806 'page_latest', 'page_is_redirect', 'page_len' )
807 ),
808 'conds' => $conds,
809 'options' => $options,
810 'join_conds' => $join_cond
811 );
812
813 ChangeTags::modifyDisplayQuery(
814 $queryInfo['tables'],
815 $queryInfo['fields'],
816 $queryInfo['conds'],
817 $queryInfo['join_conds'],
818 $queryInfo['options'],
819 $this->tagFilter
820 );
821
822 wfRunHooks( 'ContribsPager::getQueryInfo', array( &$this, &$queryInfo ) );
823
824 return $queryInfo;
825 }
826
827 function getUserCond() {
828 $condition = array();
829 $join_conds = array();
830 $tables = array( 'revision', 'page', 'user' );
831 $index = false;
832 if ( $this->contribs == 'newbie' ) {
833 $max = $this->mDb->selectField( 'user', 'max(user_id)', false, __METHOD__ );
834 $condition[] = 'rev_user >' . (int)( $max - $max / 100 );
835 # ignore local groups with the bot right
836 # @todo FIXME: Global groups may have 'bot' rights
837 $groupsWithBotPermission = User::getGroupsWithPermission( 'bot' );
838 if ( count( $groupsWithBotPermission ) ) {
839 $tables[] = 'user_groups';
840 $condition[] = 'ug_group IS NULL';
841 $join_conds['user_groups'] = array(
842 'LEFT JOIN', array(
843 'ug_user = rev_user',
844 'ug_group' => $groupsWithBotPermission
845 )
846 );
847 }
848 } else {
849 $uid = User::idFromName( $this->target );
850 if ( $uid ) {
851 $condition['rev_user'] = $uid;
852 $index = 'user_timestamp';
853 } else {
854 $condition['rev_user_text'] = $this->target;
855 $index = 'usertext_timestamp';
856 }
857 }
858
859 if ( $this->deletedOnly ) {
860 $condition[] = 'rev_deleted != 0';
861 }
862
863 if ( $this->topOnly ) {
864 $condition[] = 'rev_id = page_latest';
865 }
866
867 if ( $this->newOnly ) {
868 $condition[] = 'rev_parent_id = 0';
869 }
870
871 return array( $tables, $index, $condition, $join_conds );
872 }
873
874 function getNamespaceCond() {
875 if ( $this->namespace !== '' ) {
876 $selectedNS = $this->mDb->addQuotes( $this->namespace );
877 $eq_op = $this->nsInvert ? '!=' : '=';
878 $bool_op = $this->nsInvert ? 'AND' : 'OR';
879
880 if ( !$this->associated ) {
881 return array( "page_namespace $eq_op $selectedNS" );
882 }
883
884 $associatedNS = $this->mDb->addQuotes(
885 MWNamespace::getAssociated( $this->namespace )
886 );
887
888 return array(
889 "page_namespace $eq_op $selectedNS " .
890 $bool_op .
891 " page_namespace $eq_op $associatedNS"
892 );
893 }
894
895 return array();
896 }
897
898 function getIndexField() {
899 return 'rev_timestamp';
900 }
901
902 function doBatchLookups() {
903 # Do a link batch query
904 $this->mResult->seek( 0 );
905 $revIds = array();
906 $batch = new LinkBatch();
907 # Give some pointers to make (last) links
908 foreach ( $this->mResult as $row ) {
909 if ( isset( $row->rev_parent_id ) && $row->rev_parent_id ) {
910 $revIds[] = $row->rev_parent_id;
911 }
912 if ( isset( $row->rev_id ) ) {
913 if ( $this->contribs === 'newbie' ) { // multiple users
914 $batch->add( NS_USER, $row->user_name );
915 $batch->add( NS_USER_TALK, $row->user_name );
916 }
917 $batch->add( $row->page_namespace, $row->page_title );
918 }
919 }
920 $this->mParentLens = Revision::getParentLengths( $this->mDbSecondary, $revIds );
921 $batch->execute();
922 $this->mResult->seek( 0 );
923 }
924
925 /**
926 * @return string
927 */
928 function getStartBody() {
929 return "<ul>\n";
930 }
931
932 /**
933 * @return string
934 */
935 function getEndBody() {
936 return "</ul>\n";
937 }
938
939 /**
940 * Generates each row in the contributions list.
941 *
942 * Contributions which are marked "top" are currently on top of the history.
943 * For these contributions, a [rollback] link is shown for users with roll-
944 * back privileges. The rollback link restores the most recent version that
945 * was not written by the target user.
946 *
947 * @todo This would probably look a lot nicer in a table.
948 * @param object $row
949 * @return string
950 */
951 function formatRow( $row ) {
952 wfProfileIn( __METHOD__ );
953
954 $ret = '';
955 $classes = array();
956
957 /*
958 * There may be more than just revision rows. To make sure that we'll only be processing
959 * revisions here, let's _try_ to build a revision out of our row (without displaying
960 * notices though) and then trying to grab data from the built object. If we succeed,
961 * we're definitely dealing with revision data and we may proceed, if not, we'll leave it
962 * to extensions to subscribe to the hook to parse the row.
963 */
964 wfSuppressWarnings();
965 try {
966 $rev = new Revision( $row );
967 $validRevision = (bool)$rev->getId();
968 } catch ( MWException $e ) {
969 $validRevision = false;
970 }
971 wfRestoreWarnings();
972
973 if ( $validRevision ) {
974 $classes = array();
975
976 $page = Title::newFromRow( $row );
977 $link = Linker::link(
978 $page,
979 htmlspecialchars( $page->getPrefixedText() ),
980 array( 'class' => 'mw-contributions-title' ),
981 $page->isRedirect() ? array( 'redirect' => 'no' ) : array()
982 );
983 # Mark current revisions
984 $topmarktext = '';
985 $user = $this->getUser();
986 if ( $row->rev_id == $row->page_latest ) {
987 $topmarktext .= '<span class="mw-uctop">' . $this->messages['uctop'] . '</span>';
988 # Add rollback link
989 if ( !$row->page_is_new && $page->quickUserCan( 'rollback', $user )
990 && $page->quickUserCan( 'edit', $user )
991 ) {
992 $this->preventClickjacking();
993 $topmarktext .= ' ' . Linker::generateRollback( $rev, $this->getContext() );
994 }
995 }
996 # Is there a visible previous revision?
997 if ( $rev->userCan( Revision::DELETED_TEXT, $user ) && $rev->getParentId() !== 0 ) {
998 $difftext = Linker::linkKnown(
999 $page,
1000 $this->messages['diff'],
1001 array(),
1002 array(
1003 'diff' => 'prev',
1004 'oldid' => $row->rev_id
1005 )
1006 );
1007 } else {
1008 $difftext = $this->messages['diff'];
1009 }
1010 $histlink = Linker::linkKnown(
1011 $page,
1012 $this->messages['hist'],
1013 array(),
1014 array( 'action' => 'history' )
1015 );
1016
1017 if ( $row->rev_parent_id === null ) {
1018 // For some reason rev_parent_id isn't populated for this row.
1019 // Its rumoured this is true on wikipedia for some revisions (bug 34922).
1020 // Next best thing is to have the total number of bytes.
1021 $chardiff = ' <span class="mw-changeslist-separator">. .</span> ';
1022 $chardiff .= Linker::formatRevisionSize( $row->rev_len );
1023 $chardiff .= ' <span class="mw-changeslist-separator">. .</span> ';
1024 } else {
1025 $parentLen = 0;
1026 if ( isset( $this->mParentLens[$row->rev_parent_id] ) ) {
1027 $parentLen = $this->mParentLens[$row->rev_parent_id];
1028 }
1029
1030 $chardiff = ' <span class="mw-changeslist-separator">. .</span> ';
1031 $chardiff .= ChangesList::showCharacterDifference(
1032 $parentLen,
1033 $row->rev_len,
1034 $this->getContext()
1035 );
1036 $chardiff .= ' <span class="mw-changeslist-separator">. .</span> ';
1037 }
1038
1039 $lang = $this->getLanguage();
1040 $comment = $lang->getDirMark() . Linker::revComment( $rev, false, true );
1041 $date = $lang->userTimeAndDate( $row->rev_timestamp, $user );
1042 if ( $rev->userCan( Revision::DELETED_TEXT, $user ) ) {
1043 $d = Linker::linkKnown(
1044 $page,
1045 htmlspecialchars( $date ),
1046 array( 'class' => 'mw-changeslist-date' ),
1047 array( 'oldid' => intval( $row->rev_id ) )
1048 );
1049 } else {
1050 $d = htmlspecialchars( $date );
1051 }
1052 if ( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
1053 $d = '<span class="history-deleted">' . $d . '</span>';
1054 }
1055
1056 # Show user names for /newbies as there may be different users.
1057 # Note that we already excluded rows with hidden user names.
1058 if ( $this->contribs == 'newbie' ) {
1059 $userlink = ' . . ' . $lang->getDirMark()
1060 . Linker::userLink( $rev->getUser(), $rev->getUserText() );
1061 $userlink .= ' ' . $this->msg( 'parentheses' )->rawParams(
1062 Linker::userTalkLink( $rev->getUser(), $rev->getUserText() ) )->escaped() . ' ';
1063 } else {
1064 $userlink = '';
1065 }
1066
1067 if ( $rev->getParentId() === 0 ) {
1068 $nflag = ChangesList::flag( 'newpage' );
1069 } else {
1070 $nflag = '';
1071 }
1072
1073 if ( $rev->isMinor() ) {
1074 $mflag = ChangesList::flag( 'minor' );
1075 } else {
1076 $mflag = '';
1077 }
1078
1079 $del = Linker::getRevDeleteLink( $user, $rev, $page );
1080 if ( $del !== '' ) {
1081 $del .= ' ';
1082 }
1083
1084 $diffHistLinks = $this->msg( 'parentheses' )
1085 ->rawParams( $difftext . $this->messages['pipe-separator'] . $histlink )
1086 ->escaped();
1087 $ret = "{$del}{$d} {$diffHistLinks}{$chardiff}{$nflag}{$mflag} ";
1088 $ret .= "{$link}{$userlink} {$comment} {$topmarktext}";
1089
1090 # Denote if username is redacted for this edit
1091 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
1092 $ret .= " <strong>" .
1093 $this->msg( 'rev-deleted-user-contribs' )->escaped() .
1094 "</strong>";
1095 }
1096
1097 # Tags, if any.
1098 list( $tagSummary, $newClasses ) = ChangeTags::formatSummaryRow(
1099 $row->ts_tags,
1100 'contributions'
1101 );
1102 $classes = array_merge( $classes, $newClasses );
1103 $ret .= " $tagSummary";
1104 }
1105
1106 // Let extensions add data
1107 wfRunHooks( 'ContributionsLineEnding', array( $this, &$ret, $row, &$classes ) );
1108
1109 if ( $classes === array() && $ret === '' ) {
1110 wfDebug( "Dropping Special:Contribution row that could not be formatted\n" );
1111 $ret = "<!-- Could not format Special:Contribution row. -->\n";
1112 } else {
1113 $ret = Html::rawElement( 'li', array( 'class' => $classes ), $ret ) . "\n";
1114 }
1115
1116 wfProfileOut( __METHOD__ );
1117
1118 return $ret;
1119 }
1120
1121 /**
1122 * Overwrite Pager function and return a helpful comment
1123 * @return string
1124 */
1125 function getSqlComment() {
1126 if ( $this->namespace || $this->deletedOnly ) {
1127 // potentially slow, see CR r58153
1128 return 'contributions page filtered for namespace or RevisionDeleted edits';
1129 } else {
1130 return 'contributions page unfiltered';
1131 }
1132 }
1133
1134 protected function preventClickjacking() {
1135 $this->preventClickjacking = true;
1136 }
1137
1138 /**
1139 * @return bool
1140 */
1141 public function getPreventClickjacking() {
1142 return $this->preventClickjacking;
1143 }
1144 }